Ios – “Initializer element is not a compile-time constant” why

iosobjective cxcode

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?

Best Answer

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, static variables 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:

static NSArray *localArray = nil;
if (localArray == nil)
    localArray = [NSArray arrayWithArray: self.container.objects ];

Which is fairly similar to the code that the compiler would generate under the hood for a static variable 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 like nil here; in this case, we are assuming that localArray will never be nil). You can check out your compiler's disassembly for that if you want.