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

poe*_*poe 4 java constants objective-c

我正在尝试找到与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;
    }
}
Run Code Online (Sandbox Code Playgroud)

要么,

public static final MyObject FOO = new MyObject( "foo", 42 );
Run Code Online (Sandbox Code Playgroud)

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

foo.h中:

static MyEnumClass* FOO;
Run Code Online (Sandbox Code Playgroud)

Foo.m:

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

当我这样做并尝试使用FOO常量时,它strval变量中没有值.我通过使用实际上被调用的NSLog调用来验证initialize.

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

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

Dar*_*ren 5

使用extern而不是static:

foo.h中:

extern MyEnumClass* FOO;
Run Code Online (Sandbox Code Playgroud)

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];
    }
}
Run Code Online (Sandbox Code Playgroud)

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