【问题标题】:Check if constant is defined at runtime in Obj-C检查是否在运行时在 Obj-C 中定义了常量
【发布时间】:2011-03-08 12:31:51
【问题描述】:

例如,要访问NSDictionary 中的变量,Cocoa 框架通常会定义键,例如UIKeyboardBoundsUserInfoKey。如何检查是否在运行时定义了密钥?我找到了有关如何检查类和函数的示例,但没有找到常量。

【问题讨论】:

    标签: iphone objective-c cocoa cocoa-touch macos


    【解决方案1】:

    Jasarien 的回答大致正确,但在 LLVM 1.5 下容易出现问题,编译器将优化 if 语句。

    您还应该将常量的地址与NULL 进行比较,而不是nilnil 具有不同的语义)。

    更准确的解决方案是这样的:

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

    【讨论】:

    【解决方案2】:

    检查它的指针是否为 nil,像这样

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

    【讨论】:

    • 我添加了一个可能感兴趣的更正答案。
    • 为什么不只是if (&UIKeyboardBoundsUserInfoKey) {}
    猜你喜欢
    • 2018-05-09
    • 2020-05-13
    • 2023-03-31
    • 2012-04-27
    • 2021-04-14
    • 2012-01-20
    • 1970-01-01
    • 2010-09-22
    • 1970-01-01
    相关资源
    最近更新 更多