开发者

Check if constant is defined at runtime in Obj-C

开发者 https://www.devze.com 2023-01-05 00:00 出处:网络
To, for example, access variables in a NSDictionary Cocoa frameworks often define keys, such as UIKeyboardBoundsUserInfoKey. How can I check if a key is defined at 开发者_运维问答runtime? I found exam

To, for example, access variables in a NSDictionary Cocoa frameworks often define keys, such as UIKeyboardBoundsUserInfoKey. How can I check if a key is defined at 开发者_运维问答runtime? I found examples on how to check for classes and functions, but not for constants.


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
}


Check it's pointer against nil, like this

if (&UIKeyboardBoundsUserInfoKey != nil)
{
    //Key exists
}
0

精彩评论

暂无评论...
验证码 换一张
取 消