Objective-C相当于Java枚举或“静态最终”对象

时间:2011-03-30 00:31:37

标签: java objective-c constants

我正在尝试找到与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也会突出显示上面显示的.h文件中的行'FOO' defined but not used

我完全不知所措!谢谢你的帮助!

1 个答案:

答案 0 :(得分:5)

使用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实例,这不是您想要的。

相关问题