[Solved] “Initializer element is not a compile-time constant” why?

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?

Enquirer: subzero


Solution #1:

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.

Respondent: Adam Rosenfield

Solution #2:

You just can’t initialize a static variable with a non-static value that will be known/modified at runtime.

You should probably do something like this:

static NSArray *localArray = nil;
localArray = ...;

The first instruction will be executed once in your app lifecycle.
The second instruction will be executed every time the calculate: method is called.

Nevertheless, pay attention to the fact that using static variables can lead to buggy behaviors if not done properly so if you feel uneasy with these, you should probably not use them.

Respondent: Dirty Henry

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy