views:

221

answers:

2

The Compiler claims an error saying: "initializer element is not constant", when I try to initialize a static variable inside a method with a call to a static method (with + in its definition). Anyway I can tell him that this method always returns the same value. I know this is not the same as static method, but there seems to be no constant methods in Objective-C (other than macros which won't work here because I am calling UI_USER_INTERFACE_IDIOM() from inside the method).

+1  A: 

You cannot do that in Objective-C.

There are two solutions:

  1. Switch to Objective-C++. Change the file extension from .m to .mm.
  2. Initialize it with nil, and check it when you first use it, as in:

    static NSString*foo=nil;
    if(!foo){
          foo=[ ... ] ;
    }
    
Yuji
The nil assignment isn't strictly needed, unlike local variables static variables are nil by default.
mustISignUp
You're right. But I prefer that way, just to be sure to be sure.
Yuji
A: 

There's actually another solution in addition to Yuji's. You can create a function and prefix it with a GCC attribute (also works in Clang and LLVM) that will cause it to be executed before main() is. I've used this approach several times, and it looks something like this:

static NSString *foo;

__attribute__((constructor)) initializeFoo() {
    foo = ...;
}

When you actually use foo, it will already be initialized. This mean you don't have to check whether it's nil each time. (This is certainly a minor performance benefit, though multiplied by the number of times you use it, but it can also simplify one or more other regions of code. For example, if you reference the static variable in N different places, you might have to check for nil in all N or risk a crash. Often, people call a function or use a #define to handle initialization, and if that code is only actually used once, it can be a penalty worth removing.

Quinn Taylor