How do a populate an NSArray const? Or more generically how can I fix my code below to have an array constant (created in Constants.h & Constants.m) to be available to other parts of my code.
Was hoping to be able to access the constant as a static type object (i.e. as opposed to having to create an instance of constants.m and then access it) is this is possible.
I note the approach works OK for a string, but for NSArray the issue is populating the array.
Code:
constants.h
@interface Constants : NSObject {
}
extern NSArray * const ArrayTest;
@end
#import “Constants.h”
@implementation Constants
NSArray * const ArrayTest = [[[NSArray alloc] initWithObjects:@"SUN", @"MON", @"TUES", @"WED", @"THUR", @"FRI", @"SAT", nil] autorelease];
// ERROR - Initializer element is not a compile time constant
@end
The standard approach is to supply a class method that creates the array the first time it is requested and thereafter returns the same array. The array is never released.
A simple, example solution is this:
You can of course fancy this up with GCD instead of using an if: