Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if constant is defined at runtime in Obj-C

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.

like image 954
Johan Kool Avatar asked Jun 26 '10 00:06

Johan Kool


2 Answers

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
}
like image 74
Nathan de Vries Avatar answered Oct 21 '22 18:10

Nathan de Vries


Check it's pointer against nil, like this

if (&UIKeyboardBoundsUserInfoKey != nil)
{
    //Key exists
}
like image 30
Jasarien Avatar answered Oct 21 '22 16:10

Jasarien