【问题标题】:Objective-C equivalent of Java enums or "static final" objectsJava 枚举或“静态最终”对象的 Objective-C 等价物
【发布时间】:2011-03-30 00:31:37
【问题描述】:

我正在尝试找到与 Java 枚举类型或“公共静态最终”对象等效的 Objective-C,例如:

public enum MyEnum {
    private String str;
    private int val;
    FOO( "foo string", 42 ),
    BAR( "bar string", 1337 );
    MyEnum( String str, int val ) {
        this.str = str;
        this.val = val;
    }
}

或者,

public static final MyObject FOO = new MyObject( "foo", 42 );

我需要创建常量(当然),并且可以在导入相关 .h 文件的任何地方或全局访问。我尝试了以下方法但没有成功:

Foo.h:

static MyEnumClass* FOO;

Foo.m:

+ (void)initialize {
    FOO = [[MyEnumClass alloc] initWithStr:@"foo string" andInt:42];
}

当我这样做并尝试使用FOO 常量时,它在strval 变量中没有值。我已经通过使用NSLog 调用验证了initialize 实际上正在被调用。

此外,即使我在代码测试块中引用了FOO 变量,Xcode 还是用注释'FOO' defined but not used 突出显示了上面显示的 .h 文件中的行。

我完全糊涂了!感谢您的帮助!

【问题讨论】:

    标签: java objective-c constants


    【解决方案1】:

    使用extern 代替static

    Foo.h:

    extern MyEnumClass* FOO;
    

    Foo.m:

    MyEnumClass* FOO = nil; // This is the actual instance of FOO that will be shared by anyone who includes "Foo.h".  That's what the extern keyword accomplishes.
    
    + (void)initialize {
        if (!FOO) {
            FOO = [[MyEnumClass alloc] initWithStr:@"foo string" andInt:42];
        }
    }
    

    static 表示该变量在单个编译单元(例如,单个 .m 文件)中是私有的。因此,在头文件中使用 static 将为每个包含 Foo.h 的 .m 文件创建私有 FOO 实例,这不是您想要的。

    【讨论】:

    • +1。我要补充一点:您还必须安排调用 +[Foo intialize]。在有其他消息发送给 Foo 之前,它不会被调用。而 [FOO someMessage] 不会这样做,因为 FOO 最初是 nil。这就是为什么我们倾向于使用像 +[Foo sharedFoo] 这样的东西而不是像这样的全局变量的部分原因。
    猜你喜欢
    • 1970-01-01
    • 2021-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多