0

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

Richard J. Ross III
  • 55,009
  • 24
  • 135
  • 201
  • Is there a typo here? `Foo` is the class variable, so should the problem line read `myObj = ` instead of `Foo =`? – bosmacs Oct 22 '10 at 17:26

1 Answers1

1

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
  • 7,341
  • 4
  • 31
  • 31