在 Objective-C 中使用常量对象
我有一段与此类似的代码:
//Foo.h
OBJC_EXPORT MyObject *const myObj;
// Foo.m
MyObject *const myObj;
@implementation Foo
+(void) initialize
{
if (self = [Graph class])
{
myObj = [Config get:@"Foo"]; // <--- ERROR! assignment of read-only variable 'Foo'
// ....
}
}
// ....
@end
这需要像这样完成,因为常量变量必须从配置文件加载一次。我怎样才能以这种方式使用常量(是的,它需要是常量,因为如果它被改变,它会带来另一组问题..)?
I have a piece of code similar to this:
//Foo.h
OBJC_EXPORT MyObject *const myObj;
// Foo.m
MyObject *const myObj;
@implementation Foo
+(void) initialize
{
if (self = [Graph class])
{
myObj = [Config get:@"Foo"]; // <--- ERROR! assignment of read-only variable 'Foo'
// ....
}
}
// ....
@end
This needs to be accomplished like this, as the constant variable must be loaded exactly once from a config file. How can I use constants in that way (yes, it needs to be constants, because if it is changed, it will present a whole other group of problems..)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
可能有更好的方法,但我的第一个想法是通过额外的指针间接分配它,例如:
如果是 C++,
const_cast<>
将是合适的,但我不确定最常见/等效的 C 习惯用法。There's likely a better way, but my first thought is assign it through an extra pointer indirection, e.g.:
If it were C++,
const_cast<>
would be appropriate, but I'm unsure as to the most common/equivalent C idiom.