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
常量时,它str
和val
变量中没有值.我通过使用实际上被调用的NSLog
调用来验证initialize
.
此外,即使我FOO
在代码的测试块中引用变量,Xcode 也会使用注释突出显示上面显示的.h文件中的行'FOO' defined but not used
.
我完全不知所措!谢谢你的帮助!
使用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实例,这不是您想要的.
归档时间: |
|
查看次数: |
2428 次 |
最近记录: |