【发布时间】:2011-03-08 12:31:51
【问题描述】:
例如,要访问NSDictionary 中的变量,Cocoa 框架通常会定义键,例如UIKeyboardBoundsUserInfoKey。如何检查是否在运行时定义了密钥?我找到了有关如何检查类和函数的示例,但没有找到常量。
【问题讨论】:
标签: iphone objective-c cocoa cocoa-touch macos
例如,要访问NSDictionary 中的变量,Cocoa 框架通常会定义键,例如UIKeyboardBoundsUserInfoKey。如何检查是否在运行时定义了密钥?我找到了有关如何检查类和函数的示例,但没有找到常量。
【问题讨论】:
标签: iphone objective-c cocoa cocoa-touch macos
Jasarien 的回答大致正确,但在 LLVM 1.5 下容易出现问题,编译器将优化 if 语句。
您还应该将常量的地址与NULL 进行比较,而不是nil(nil 具有不同的语义)。
更准确的解决方案是这样的:
BOOL isKeyboardBoundsKeyAvailable = (&UIKeyboardBoundsUserInfoKey != NULL);
if (isKeyboardBoundsKeyAvailable) {
// UIKeyboardBoundsUserInfoKey defined
}
【讨论】:
#ifdef?
检查它的指针是否为 nil,像这样
if (&UIKeyboardBoundsUserInfoKey != nil)
{
//Key exists
}
【讨论】:
if (&UIKeyboardBoundsUserInfoKey) {} ?