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?
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];
});
}
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];
});
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With