开发者

Using constant objects in objective-c

开发者 https://www.devze.com 2023-01-22 02:42 出处:网络
I have a piece of code similar to this: //Foo.h OBJC_EXPORT MyObject *const myObj; // Foo.m MyObject *const myObj;

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号