static initializers in objective C

Joey picture Joey · Feb 16, 2011 · Viewed 8.1k times · Source

How do I make static initializers in objective-c (if I have the term correct). Basically I want to do something like this:

static NSString* gTexts[] = 
{
    @"A string.",
    @"Another string.",
}

But I want to do this more struct-like, i.e. have not just an NSString for each element in this array, but instead an NSString plus one NSArray that contains a variable number of MyObjectType where MyObjectType would contain an NSString, a couple ints, etc.

Answer

Dave DeLong picture Dave DeLong · Feb 16, 2011

Since NSArrays and MyObjectTypes are heap-allocated objects, you cannot create them in a static context. You can declare the variables, and then initialize them in a method.

So you cannot do:

static NSArray *myStaticArray = [[NSArray alloc] init....];

Instead, you must do:

static NSArray *myStaticArray = nil;

- (void) someMethod {
  if (myStaticArray == nil) {
    myStaticArray = [[NSArray alloc] init...];
  }
}

This happens to work with constant strings (@"foo", etc), because they are not heap-allocated. They are hardcoded into the binary.