In Objective-C, objects can only be allocated in heap, so there's no way to create an NSArray in static memory. However, you can create a C array of pointers to NSString constants like so...
NSString * const kLabelNames[] = {
@"Foo", @"Bar", @"Baz"
};
...and then you can write class methods like this one...
+ (NSArray *)labelNames
{
static NSArray *names;
if (names == nil) {
names = [[NSArray alloc] initWithObjects:kLabelNames count:3];
}
return names;
}
Edit
Note that with the introduction of new technologies such as ARC, Grand Central Dispatch and the new literal syntax for arrays, there's now a more straightforward way to accomplish something similar. Note that the example below also provides greater thread safety, though the original example could have incorporated an @synchronized
block, or one of several other mechanisms, to achieve similar results.
+ (NSArray *)labelNames
{
static NSArray *names;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
names = @[@"Foo", @"Bar", @"Baz"];
});
return names;
}
However the above example doesn't completely address the original question though. If a global constant array is truly needed, the preceding example could be rewritten along similar lines as the original answer, while still taking advantage of GCD:
NSString * const kLabelNames[] = {
@"Foo", @"Bar", @"Baz"
};
+ (NSArray *)labelNames
{
static NSArray *names;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
names = [NSArray arrayWithObjects:kLabelNames count:3];
});
return names;
}