检查Obj-C中是否在运行时定义了常量 [英] Check if constant is defined at runtime in Obj-C

查看:115
本文介绍了检查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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆