【问题标题】:How are constants initialized in Objective-C header files?Objective-C 头文件中的常量是如何初始化的?
【发布时间】:2010-05-31 09:44:37
【问题描述】:

如何初始化头文件中的常量?

例如:

@interface MyClass : NSObject {

  const int foo;

}

@implementation MyClass

-(id)init:{?????;}

【问题讨论】:

    标签: objective-c header constants


    【解决方案1】:

    对于“公共”常量,您在头文件 (.h) 中将其声明为 extern,并在实现文件 (.m) 中对其进行初始化。

    // File.h
    extern int const foo;
    

    然后

    // File.m
    int const foo = 42;
    

    考虑使用enum,如果它不仅仅是一个,而是多个属于一起的常量

    【讨论】:

    • 如果我需要typedef NS_ENUM怎么办?
    【解决方案2】:

    Objective C 类不支持将常量作为成员。您无法按照自己的方式创建常量。

    声明与类关联的常量最接近的方法是定义返回它的类方法。您也可以使用 extern 直接访问常量。两者都在下面演示:

    // header
    extern const int MY_CONSTANT;
    
    @interface Foo
    {
    }
    
    +(int) fooConstant;
    
    @end
    
    // implementation
    
    const int MY_CONSTANT = 23;
    
    static const int FOO_CONST = 34;
    
    @implementation Foo
    
    +(int) fooConstant
    {
        return FOO_CONST; // You could also return 34 directly with no static constant
    }
    
    @end
    

    类方法版本的一个优点是它可以很容易地扩展为提供常量对象。您可以使用外部对象,但您必须在初始化方法中初始化它们(除非它们是字符串)。所以你会经常看到如下模式:

    // header
    @interface Foo
    {
    }
    
    +(Foo*) fooConstant;
    
    @end
    
    // implementation
    
    @implementation Foo
    
    +(Foo*) fooConstant
    {
        static Foo* theConstant = nil;
        if (theConstant == nil)
        {
            theConstant = [[Foo alloc] initWithStuff];
        }
        return theConstant;
    }
    
    @end
    

    【讨论】:

    • 添加了我刚刚想到的一点
    • 不错。指定您编写的模式称为单例模式并且通常用于跨应用程序共享内容可能会很有趣。 iPhone 开发中的一个很好的例子是 AppDelegate 类。
    【解决方案3】:

    对于像整数这样的值类型常量,一种简单的方法是使用 enum hack,正如 unbeli 所暗示的那样。

    // File.h
    enum {
        SKFoo = 1,
        SKBar = 42,
    };
    

    与使用 extern 相比,这样做的一个优点是它在编译时全部解析,因此不需要内存来保存变量。

    另一种方法是使用static const,这是在 C/C++ 中替换枚举破解的方法。

    // File.h
    static const int SKFoo = 1;
    static const int SKBar = 42;
    

    快速浏览 Apple 的标头表明 enum hack 方法似乎是在 Objective-C 中执行此操作的首选方法,我实际上发现它更简洁并自己使用它。

    另外,如果您正在创建选项组,您应该考虑使用NS_ENUM 来创建类型安全的常量。

    // File.h
    typedef NS_ENUM(NSInteger, SKContants) {
        SKFoo = 1,
        SKBar = 42,
    };
    

    有关NS_ENUM 及其表弟NS_OPTIONS 的更多信息,请访问NSHipster

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2011-01-08
      • 1970-01-01
      相关资源
      最近更新 更多