【问题标题】:ifdef syntax doesn't workifdef 语法不起作用
【发布时间】:2012-09-13 16:39:48
【问题描述】:
我想根据不同的设备高度动态定义一个常数。
我尝试使用此代码,但它不起作用:
#define isPhone568 ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone && [UIScreen mainScreen].bounds.size.height == 568)
#ifdef isPhone568
#define kColumnHeightPortrait568 548
#else
#define kColumnHeightPortrait568 (IS_IPAD ? 984 : 460)
#endif
即使我使用的是 3.5" 模拟器,我也得到 548。这有什么问题?
【问题讨论】:
标签:
iphone
objective-c
ios
macros
conditional-compilation
【解决方案1】:
您不能在宏定义中运行代码,这是一个在编译时发生的简单文本替换过程。因此,您不知道当时的设备特性是什么,因为您没有在目标设备上。
如果您想使用[UIDevice currentDevice] userInterfaceIdiom 之类的东西,您必须在运行时评估它, 而不是在编译时宏中,例如:
int kColumnHeightPortrait568 = 548;
if (([[UIDevice currentDevice] userInterfaceIdiom] != UIUserInterfaceIdiomPhone)
|| ([UIScreen mainScreen].bounds.size.height != 568))
{
kColumnHeightPortrait568 = (IS_IPAD ? 984 : 460);
}
【解决方案2】:
#ifdef 用于检查是否定义了宏。当您在第一行定义 isPhone568 时,#ifdef isPhone568 将为真。
如果您想测试表达式的值而不是宏的存在,您应该改用#if。但是#if 只能测试简单的算术表达式,就像 paxdiablo 提到的,“你不能在宏定义中运行代码”。