Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do a populate an NSArray const? (code not working included)

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
like image 789
Greg Avatar asked Jul 26 '26 22:07

Greg


1 Answers

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:

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

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

You can of course fancy this up with GCD instead of using an if:

/* Implementation */
+ (NSArray *)someValues
{
    static NSArray *sSomeValues;
    static dispatch_once_t sInitSomeValues;
    dispatch_once(&sInitSomeValues, ^{
        sSomeValues = [[NSArray alloc]
                       initWithObjects:/*objects*/, (void *)nil];
    });
    return sSomeValues;
}
like image 92
Jeremy W. Sherman Avatar answered Jul 28 '26 14:07

Jeremy W. Sherman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!