Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

iphone - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...