How to fill NSArray const? (code does not work)

How to fill NSArray const? Or more universally, how can I fix my code below to have a constant array (created in Constants.h and Constants.m) to access other parts of my code.

I would like to be able to access the constant as an object of a static type (i.e., unlike the need to create an instance of the .m constants and then access it), this is possible.

I note that the approach works fine for a string, but for NSArray, the problem is filling the array.

the 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
+3
source share
1 answer

, , . .

:

/* Interface */
+ (NSArray *)someValues;

/* Implementation */
+ (NSArray *)someValues
{
    static NSArray *sSomeValues;
    if (!sSomeValues) {
        sSomeValues = [[NSArray alloc]
                       initWithObjects:/*objects*/, (void *)nil];
    }
    return sSomeValues;
}

, GCD if:

/* Implementation */
+ (NSArray *)someValues
{
    static NSArray *sSomeValues;
    static dispatch_once_t sInitSomeValues;
    dispatch_once(&sInitSomeValues, ^{
        sSomeValues = [[NSArray alloc]
                       initWithObjects:/*objects*/, (void *)nil];
    });
    return sSomeValues;
}
+6

All Articles