0

下面的代码应该显示运行应用程序的设备的型号/设备名称。例如,如果应用程序在第一代 iPod 上运行,我希望它显示“iPod1,1”。当我运行应用程序时,标签为空。我究竟做错了什么?

#import "ViewController.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@interface ViewController ()

@end

@implementation ViewController
@synthesize label;

- (void)viewDidLoad
{
    label.text = [self platformString];
    [self platformCapabilities];

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (NSString *) platform
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
NSString *platform = [NSString stringWithCString:machine encoding: NSUTF8StringEncoding];
free(machine);
return platform;
}

- (int) platformType
{
NSString *platform = [self platform];
if ([platform isEqualToString:@"iPhone1,1"]) return UIDevice1GiPhone;
if ([platform isEqualToString:@"iPhone1,2"]) return UIDevice3GiPhone;
if ([platform isEqualToString:@"iPod1,1"])   return UIDevice1GiPod;
if ([platform isEqualToString:@"iPod2,1"])   return UIDevice2GiPod;
if ([platform hasPrefix:@"iPhone"]) return UIDeviceUnknowniPhone;
if ([platform hasPrefix:@"iPod"]) return UIDeviceUnknowniPod;
return UIDeviceUnknown;
}

- (NSString *) platformString
{
switch ([self platformType])
{
    case UIDevice1GiPhone: return IPHONE_1G_NAMESTRING;
    case UIDevice3GiPhone: return IPHONE_3G_NAMESTRING;
    case UIDeviceUnknowniPhone: return IPHONE_UNKNOWN_NAMESTRING;

    case UIDevice1GiPod: return IPOD_1G_NAMESTRING;
    case UIDevice2GiPod: return IPOD_2G_NAMESTRING;
    case UIDeviceUnknowniPod: return IPOD_UNKNOWN_NAMESTRING;

    default: return nil;
}
}

- (int) platformCapabilities
{
switch ([self platformType])
{
    case UIDevice1GiPhone: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;
    case UIDevice3GiPhone: return UIDeviceSupportsGPS | UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;
    case UIDeviceUnknowniPhone: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInCamera | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone | UIDeviceSupportsTelephony | UIDeviceSupportsVibration;

    case UIDevice1GiPod: return 0;
    case UIDevice2GiPod: return UIDeviceBuiltInSpeaker | UIDeviceBuiltInMicrophone | UIDeviceSupportsExternalMicrophone;
    case UIDeviceUnknowniPod: return 0;

    default: return 0;
}
}
@end

另外,如何扩展此代码以识别第 3 代 iPod、第 4 代 iPod 等?

4

2 回答 2

0

我建议使用 Erica 的 UIDevice-Extensions 类别来实现您的目标。

https://github.com/erica/uidevice-extension

几乎所有类型的自省代码都可以用于您的应用程序运行的设备类型。

于 2012-09-10T20:41:59.307 回答
0

你一定是在打你的零案。您是否尝试进入平台方法以查看它返回的内容以及是否与您的任何情况相匹配?

于 2012-09-10T20:42:59.347 回答