检查Obj-C中是否在运行时定义了常量

Joh*_*ool 20 iphone macos cocoa cocoa-touch objective-c

例如,在NSDictionaryCocoa框架中访问变量通常会定义键,例如UIKeyboardBoundsUserInfoKey.如何检查是否在运行时定义了键?我找到了关于如何检查类和函数的示例,但没有找到常量.

Nat*_*ies 46

Jasarien的答案大致正确,但在LLVM 1.5下容易出现问题,编译器将优化if语句.

您还应该将常量的地址与(NULL而不是具有不同的语义)进行比较.nilnil

更准确的解决方案是:

BOOL isKeyboardBoundsKeyAvailable = (&UIKeyboardBoundsUserInfoKey != NULL);
if (isKeyboardBoundsKeyAvailable) {
  // UIKeyboardBoundsUserInfoKey defined
}
Run Code Online (Sandbox Code Playgroud)


Jas*_*ien 30

检查它的指针是否为nil,就像这样

if (&UIKeyboardBoundsUserInfoKey != nil)
{
    //Key exists
}
Run Code Online (Sandbox Code Playgroud)

  • 我添加了一个可能有意义的修正答案. (3认同)