Objective-C等效的Java枚举或“静态最终”对象 [英] Objective-C equivalent of Java enums or "static final" objects
问题描述
我正在尝试找到与Java枚举类型或公共静态最终对象等效的Objective-C,例如:
I'm trying to find an Objective-C equivalent to either Java enum types, or "public static final" objects, like:
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文件,或全局。我试过以下但没有成功:
I need to create constants that are constants (of course), and accessible anywhere that imports the associated .h file, or globally. I've tried the following with no success:
Foo.h:
static MyEnumClass* FOO;
Foo.m:
+ (void)initialize {
FOO = [[MyEnumClass alloc] initWithStr:@"foo string" andInt:42];
}
当我这样做并尝试使用 FOO时
常量,它在 str
和 val
变量中没有值。我已经通过使用 NSLog
验证了 initialize
实际上正在被调用。
When I did this and tried to use the FOO
constant, it had no values in the str
and val
variables. I have verified through the use of NSLog
calls that initialize
is in fact being called.
另外,即使我在测试代码块中引用 FOO
变量,Xcode也会突出显示上面显示的.h文件中的行。评论'FOO'定义但未使用
。
Also, even though I am referencing the FOO
variable in the test block of code, Xcode highlighted the line in the .h file shown above with the comment 'FOO' defined but not used
.
我完全不知所措!感谢您的帮助!
I'm totally baffled! Thanks for any help!
推荐答案
使用 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实例,这不是您想要的。
static
means that the variable is private within a single compilation unit (e.g., a single .m file). So using static
in a header file will create private FOO instances for each .m file that includes Foo.h, which is not what you would ever want.
这篇关于Objective-C等效的Java枚举或“静态最终”对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!