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.
The +initialize method is called automatically the first time a class is used, before any class methods are used or instances are created.
+initialize is inherited by subclasses, and is also called for each subclasses that doesn't implement an +initialize of their own. This can be especially problematic if you naively implement singleton initialization in +initialize. The solution is to check the type of the class variable.
p.s You should never call +initialize yourself.
Since
NSArrays
andMyObjectTypes
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:
Instead, you must do:
This happens to work with constant strings (
@"foo"
, etc), because they are not heap-allocated. They are hardcoded into the binary.here's one way, if you can live with an objc++ translation:
It is very important that you make sure that your static initialization is thread-safe (available in iOS 4.1+)!!!