Search code examples
objective-cstaticinitializer

static initializers in objective C


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.


Solution

  • 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.