【问题标题】:Comparing #define giving incorrect result比较 #define 给出不正确的结果
【发布时间】:2013-12-09 14:58:33
【问题描述】:

我定义了一个变量,输出如下。

iPhone 4 >> 4
iPhone 5 >> 5
iPad >> 999

使用的功能如下。

#define iPhone4Or5 [[UIScreen mainScreen] bounds].size.height == 568 ? 5 :
        ([[UIScreen mainScreen] bounds].size.height == 480 ? 4 : 999)

当我使用 NSLog 变量 iPhone4Or5 时,它为我提供了 iPhone 5 的正确结果,但是当我进行比较时,它给了我错误的结果...

if (iPhone4Or5==999) {
    NSLog("Its iPad version");
} else {
    NSLog("Its iPhone version");
}

当我在 iPhone 5 或更高版本上运行时,它总是给我 NSLog 作为它的 iPad 版本

知道为什么我会得到错误的比较结果吗?

我在prefix.pch中定义变量

注意:

如果我执行NSLog("iPhone4Or5==%d", iPhone4Or5),我会得到iPhone4Or5==5的输出

【问题讨论】:

  • 当设备/模拟器处于横向模式时你会做什么?身高不就是别的吗? IE。纵向模式的宽度..
  • 这里不要使用宏。您使用它们的方式是一种反模式。 ;)
  • 如果您坚持使用宏,请确保使用足够的括号以避免运算符优先级问题和其他陷阱。
  • @matsr : 我的应用程序仅是肖像模式 :D :P

标签: ios objective-c c-preprocessor


【解决方案1】:

您遇到了运算符优先级问题 - 您的宏需要括号:

#define iPhone4Or5 ([[UIScreen mainScreen] bounds].size.height == 568 ? 5 : \
        ([[UIScreen mainScreen] bounds].size.height == 480 ? 4 : 999))

更好的是,避免这个和其他常见的与宏相关的问题,而是使用函数:

int iPhone4Or5(void)
{
    const int height = [[UIScreen mainScreen] bounds].size.height;
    if (height == 568) return 5;
    if (height == 480) return 4;
    return 999;
}

【讨论】:

  • 只是好奇,括号是什么问题?我担心的是当我得到 5 的值时,为什么比较会给出错误的结果?
  • 它工作得很好,但只是好奇括号有什么不同?
  • 当您为 if (iPhone4Or5==999) 扩展宏时,== 999 术语将作为第二个三元表达式的一部分进行评估,而不是应用于宏中定义的整个复合表达式 - 这就是为什么您需要括号。这是真正的基本 C 知识,如果您打算在未来进行任何认真的编程,您应该了解这些内容。
【解决方案2】:

记录[UIScreen mainScreen] bounds].size.height的值并检查它是否为480。

或者你可以使用这些。

#define IS_IPAD ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] && [[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad) 

#define IS_IPHONE5 ((( !IS_IPAD && [[UIScreen mainScreen] bounds].size.height == 568))?YES:NO)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-30
    • 2019-05-29
    • 2012-08-27
    • 2017-12-14
    • 2019-03-12
    • 1970-01-01
    相关资源
    最近更新 更多