【问题标题】:iPhone / iPad macro or c function?iPhone/iPad 宏还是c 函数?
【发布时间】:2014-02-14 02:52:11
【问题描述】:
定义以下三元运算符的最佳方法是什么?
[[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? x : y
我考虑过使用宏
#define phonePad(x, y) ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? x : y)
但是this article 提到这可能不是最好的主意。有没有办法使用 C 函数来做等效的事情,或者这是实现它的最佳方式?
【问题讨论】:
标签:
ios
objective-c
c
macros
【解决方案1】:
我不会为此使用宏。通过使用宏,您需要设备在每次使用它时检查用户界面惯用语,并相应地设置 x 或 y。考虑创建一个基于接口习语返回的新方法。这可以是静态的,因为这个值不可能在运行时改变。
- (id)determineXOrY {
static id obj = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
obj = [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? x : y
});
return obj;
}
【解决方案2】:
都没有。
BOOL isiPhone = ([[UIDevice currentDevice] userInterfaceIdiom]
== UIUserInterfaceIdiomPhone);
foo = isiPhone ? x : y;
bar = isiPhone ? xprime : yprime;
...
如果你把它变成一个宏,你会在 Objective-C 运行时得到一堆不必要的调用。所以只需缓存结果。另外,如果你只写纯 C 代码而不是使用宏,它可能会更容易阅读。
【解决方案3】:
如果您确实使用宏,则必须添加一些括号:
#define phonePad(x, y) ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone ? (x) : (y))
如果x 或y 不仅仅是简单的值,那么如果没有括号,您将遇到严重的问题。
宏的一个缺点是,您确实需要确保 x 和 y 评估为相同的明确数据类型。