gpt4 book ai didi

java - Objective-C 相当于 Java 枚举或 "static final"对象

转载 作者:搜寻专家 更新时间:2023-10-30 19:40:36 24 4
gpt4 key购买 nike

我试图找到一个 Objective-C 等同于 Java 枚举类型或“public static final”对象,例如:

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 实际上正在被调用。

此外,即使我在代码测试 block 中引用了 FOO 变量,Xcode 仍然突出显示了上面显示的 .h 文件中的行,其中注释 'FOO' 已定义但未定义使用

我真的很困惑!感谢您的帮助!

最佳答案

使用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 文件)中是私有(private)的。因此,在头文件中使用 static 将为包含 Foo.h 的每个 .m 文件创建私有(private) FOO 实例,这不是您想要的。

关于java - Objective-C 相当于 Java 枚举或 "static final"对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480583/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com