检查Obj-C中是否在运行时定义了常量 [英] Check if constant is defined at runtime in Obj-C
问题描述
例如,要访问 NSDictionary
Cocoa框架中的变量,通常会定义键,例如 UIKeyboardBoundsUserInfoKey
。如何检查是否在运行时定义了键?我找到了关于如何检查类和函数的示例,但没有找到常量。
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的答案大致正确,但是在LLVM 1.5下容易出现问题,编译器会优化if语句。
Jasarien's answer is roughly correct, but is prone to issues under LLVM 1.5 where the compiler will optimise the if-statement away.
你还应该将常量的地址与 NULL进行比较
,而不是 nil
( nil
具有不同的语义)。
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
}
这篇关于检查Obj-C中是否在运行时定义了常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!