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.
Asked
Active
Viewed 4,492 times
20

Johan Kool
- 15,637
- 8
- 64
- 81
2 Answers
46
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
}

Nathan de Vries
- 15,481
- 4
- 49
- 55
-
Why not using `#ifdef`? – Iulian Onofrei Oct 29 '14 at 11:56
-
1@lulian #ifdef works with #define'd macros https://gcc.gnu.org/onlinedocs/cpp/Ifdef.html besides OP asked for a runtime check, which #ifdef won't do. – Emanuel Mar 10 '15 at 18:51
30
Check it's pointer against nil, like this
if (&UIKeyboardBoundsUserInfoKey != nil)
{
//Key exists
}

Jasarien
- 58,279
- 31
- 157
- 188
-
3I've added an answer with a correction which might be of interest. – Nathan de Vries Mar 11 '11 at 03:08
-
1