2010-06-26 76 views
20

例如,對於一個NSDictionary Cocoa框架中的訪問變量通常會定義鍵,例如UIKeyboardBoundsUserInfoKey。如何檢查運行時是否定義了密鑰?我找到了關於如何檢查類和函數的例子,但不是常量。檢查是否在運行時定義了常量Obj-C

回答

45

Jasarien的回答大致是正確的,但很容易出現LLVM 1.5下的問題編譯器將優化if語句了。

您還應該比較常數的地址爲NULL,而不是nilnil有不同的語義)。

一個更準確的解決方案是這樣的:

BOOL isKeyboardBoundsKeyAvailable = (&UIKeyboardBoundsUserInfoKey != NULL); 
if (isKeyboardBoundsKeyAvailable) { 
    // UIKeyboardBoundsUserInfoKey defined 
} 
+0

爲什麼不使用'#ifdef'? – 2014-10-29 11:56:47

+1

@lulian #ifdef使用#define'd宏https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html除OP之外請求運行時檢查,#ifdef不會這樣做。 – Emanuel 2015-03-10 18:51:16

29

檢查它的反對零指針,這樣

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

感謝,工程巨大。 – 2010-06-26 00:15:14

+3

我已經添加了一個可能有興趣的更正的答案。 – 2011-03-11 03:08:12

+1

爲什麼不只是'if(&UIKeyboardBoundsUserInfoKey){}'? – 2016-01-18 13:54:12