您的位置:首页 > 其它

iPhone开发技巧之环境篇(7)--- 区分不同版本的iPhone

2011-05-17 21:33 363 查看

执行环境

可以从 UIDevice 的属性 model 得到在现在执行的环境。例子如下:

1
2
3
4
5
6
7
8
9
10

NSString *modelname = [[UIDevice currentDevice]model];
if ([modelname isEqualToString:@"iPhone"]) {
// iPhone
}
if ([modelname isEqualToString:@"IPod Touch"]) {
// iPod touch
}
if ([modelname isEqualToString:@"iPhone Simulator"]) {
// iPhone Simulator
}

或者

1
2
3
4
5
6
7
8
9
1011
12
13

#import <TargetConditionals.h>

#if TARGET_OS_IPHONE
// iPhone Device
#endif

#if TARGET_IPHONE_SIMULATOR
// iPhone Simulator
#endif

#if !TARGET_IPHONE_SIMULATOR
// iPhone Device
#endif

iPhone 机器版本

可以通过 uname 函数取得当前机器的版本。例子如下:

1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19
20
21
22

struct utsname u;
uname(&u);
NSString *machine = [NSString stringWithCString:u.machine];

if ([machine isEqualToString:@"iPhone1,1"]) {
// iPhone 1G
}
if ([machine isEqualToString:@"iPhone1,2"]) {
// iPhone 3G
}
if ([machine isEqualToString:@"iPhone2,1"]) {
// iPhone 3GS
}
if ([machine isEqualToString:@"iPod1,1"]) {
// iPod touch 1G
}
if ([machine isEqualToString:@"iPod2,1"]) {
// iPod touch 2G
}
if ([machine isEqualToString:@"iPod3,1"]) {
// iPod touch Late2009
}

或者通过 sysctlbyname() 函数取得:

1
2
3
4
5
6
7
8
9
1011
12
13
14
15
16
17
18
19

- (NSString *) platform
{
size_t size;
sysctlbyname("hw.machine", NULL, &size, NULL, 0);
char *machine = malloc(size);
sysctlbyname("hw.machine", machine, &size, NULL, 0);
/*
Possible values:
"iPhone1,1" = iPhone 1G
"iPhone1,2" = iPhone 3G
"iPhone2,1" = iPhone 3GS
"iPod1,1"   = iPod touch 1G
"iPod2,1"   = iPod touch 2G
*/
NSString *platform = [NSString stringWithCString:machine];

free(machine);
return platform;
}

iPhone OS 版本

可以使用 UIDevice 的属性 systemVersion 来得到。例子如下:

1
2
3
4
5
6
7
8
9
10

NSString *osversion = [UIDevice currentDevice].systemVersion;
if ([osversion isEqualToString:@"2.1"]) {
// iPhone
}
if ([osversion isEqualToString:@"2.2.1"]) {
// iPod touch
}
if ([osversion isEqualToString:@"3.0"]) {
// iPhone Simulator
}

这里有一个别人写好的类库,专门用来得到系统版本信息,用起来比较方便。

iPhone SDK 版本宏

就像在windows系统下用 WINVER 宏来判断 windows 系统版本一样,iPhone OS 中也有类似的宏。

1
2
3
4

// 当前系统支持的最小版本
__IPHONE_OS_VERSION_MIN_REQUIRED
// 当前系统支持的最大版本
__IPHONE_OS_VERSION_MAX_ALLOWED

比如用 iPhone OS SDK 3.1.2 编译的程序

1
2

__IPHONE_OS_VERSION_MIN_REQUIRED == __IPHONE_3_0
__IPHONE_OS_VERSION_MAX_ALLOWED == __IPHONE_3_1

这时,我们可以在程序中使用下面类似的 $ifdef 语句:

1
2
3
45

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_2_2
// iPhone OS SDK 3.0 以后版本的处理
#else
// iPhone OS SDK 3.0 之前版本的处理
#endif

又或者 iPhone OS SDK 4 推出的时候,可以:

1
2
3
45
6
7
8
9

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_2_2
#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_3_1
// iPhone OS SDK 4.0 以后版本的处理
#else
// iPhone OS SDK 3.0 ~ 4.0 版本的处理
#endif
#else
// iPhone OS SDK 3.0 之前版本的处理
#endif

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: