How can I use an NSArray as a global constant?
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;}
Here's a much simpler approach:
Declare NSString with comma separated elements (or whatever delimiter you want)
NSString *const kLabelNames = @"Foo,Bar,Baz";
Then convert to NSArray whenever you need it:
NSArray *namesArray = [kLabelNames componentsSeparatedByString:@","];
If you want a set of constants that includes NS types, consider placing them all in a singleton.
You could have a single header file, and multiple implementation files (one per target). As long as that all implement the class declared in the header file you should be fine.