I have this code:
- (NSString *) calculate: (uint) position {
static NSArray * localArray = [NSArray arrayWithArray: self.container.objects ];
// some un related code
return obj;
}
The compiler complains saying: “Initializer element is not a compile-time constant”. It happened when I added “static” to localArray. But why?
Because
[NSArray arrayWithArray: self.container.objects ]isn’t a compile-time constant, it’s an expression that must be evaluated at runtime. In C and Objective-C,staticvariables inside functions must be initialized with compile-time constants, whereas C++ and Objective-C++ are more lenient and allow non-compile-time constants.Either compile your code as Objective-C++, or refactor it into something like this:
Which is fairly similar to the code that the compiler would generate under the hood for a
staticvariable initialized with a non-compile-time constant anyways (in actuality, it would use a second global flag indicating if the value was initialized, rather than using a sentinel value likenilhere; in this case, we are assuming thatlocalArraywill never benil). You can check out your compiler’s disassembly for that if you want.