views:

15

answers:

1

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..)?

+1  A: 

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.

bosmacs
ah, this worked, thanks!
Richard J. Ross III