下面的代码应该显示运行应用程序的设备的型号/设备名称。例如,如果应用程序在第一代 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 等?