Alex Rivera | Logout

static initializers in objective C

Asked 2011-02-16T05:47:17.760
10

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.

Edit
Report

1 Answer

15

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.

answered 2011-02-16T05:52:24.890

Your Answer