Objective-c static initializer NSArray

I have this code (a small part of the majority - only this nasty 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, saying

 Initializer element is not a compile-time constant 

Removing statics from the second line makes the compiler happy.

What am I / doing wrong or wrong?

+6
source share
2 answers

If the initializer of your static variable is not a compile-time constant, you need to use a different initialization mechanism, for example dispatch_once :

 -(void)determineBestFileSizeWithLimit:(int)limit { static NSString *largeName = kSizeLarge; static NSArray *nameArray = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ nameArray = @[kSizeLarge]; }); } 
+8
source

NSArray literals are not compile-time constants, as you discovered. You must 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]; }); ... } 
+4
source

All Articles