Check if constant is defined at runtime in Obj-C

前端 未结 2 675
一向
一向 2020-12-14 08:56

To, for example, access variables in a NSDictionary Cocoa frameworks often define keys, such as UIKeyboardBoundsUserInfoKey. How can I check if a k

相关标签:
2条回答
  • 2020-12-14 09:19

    Check it's pointer against nil, like this

    if (&UIKeyboardBoundsUserInfoKey != nil)
    {
        //Key exists
    }
    
    0 讨论(0)
  • 2020-12-14 09:23

    Jasarien's answer is roughly correct, but is prone to issues under LLVM 1.5 where the compiler will optimise the if-statement away.

    You should also be comparing the address of the constant to NULL, rather than nil (nil has different semantics).

    A more accurate solution is this:

    BOOL isKeyboardBoundsKeyAvailable = (&UIKeyboardBoundsUserInfoKey != NULL);
    if (isKeyboardBoundsKeyAvailable) {
      // UIKeyboardBoundsUserInfoKey defined
    }
    
    0 讨论(0)
提交回复
热议问题