Using constant objects in objective-c
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..)?
There's likely a better way, but my first thought is assign it through an extra pointer indirection, e.g.:
MyObject** nonConstObj = (MyObject**)&myObj;
*nonConstObj = [Config get:@"Foo"];
If it were C++, const_cast<>
would be appropriate, but I'm unsure as to the most common/equivalent C idiom.
精彩评论