Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-c static NSArray initializer

I have this code (small piece from a larger portion - just the troublesome part shown here):

#define kSizeLarge @"large"

-(void)determineBestFileSizeWithLimit:(int)limit
{
    static NSString *largeName = kSizeLarge;
    static NSArray *nameArray = @[kSizeLarge];
    ...
}

The compiler loves the first static variable and hates the second one, saying

Initializer element is not a compile-time constant

Removing the static from the second line makes the compiler happy.

What am/was I doing wrong or not getting correctly?

like image 521
Cubs Fan Ron Avatar asked Oct 30 '12 14:10

Cubs Fan Ron


2 Answers

When the initializer of your static variable is not a compile-time constant, you need to use another initialization mechanism, such as dispatch_once:

-(void)determineBestFileSizeWithLimit:(int)limit {
    static NSString *largeName = kSizeLarge;
    static NSArray *nameArray = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        nameArray = @[kSizeLarge];
    });
}
like image 69
Sergey Kalinichenko Avatar answered Sep 29 '22 11:09

Sergey Kalinichenko


NSArray literals are not compile-time constants as you have discovered. You should use dispatch_once to initialize the array.

#define kSizeLarge @"large"

-(void)determineBestFileSizeWithLimit:(int)limit
{
    static NSString *largeName = kSizeLarge;
    static NSArray *nameArray = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        nameArray = @[kSizeLarge];
    });
    ...
}
like image 30
Joe Avatar answered Sep 29 '22 11:09

Joe