Objective C: Initializing a static variable when calling a static method

The compiler asserts the error "initialization element is not constant" when I try to initialize a static variable inside a method with a call to the 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 a static method, but in Objective-C (other than macros that won't work here, there seems to be no constant methods because I call UI_USER_INTERFACE_IDIOM () from within the method).

+2


a source to share


2 answers


You cannot do this in Objective-C.

There are two solutions:



  • Switch to Objective-C ++. Change the file extension from .m

    to .mm

    .
  • Initialize it with nil

    and test it on first use, for example:

    static NSString*foo=nil;
    if(!foo){
          foo=[ ... ] ;
    }
    
          

+1


a source


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), which will cause it to execute before main()

. I have used this approach several times and it looks something like this:

static NSString *foo;

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

      



When you actually use it foo

, it will already be initialized. This means you don't have to check to see if it will be there nil

every time. (This, of course, a slight performance advantage, although multiplied by the number of times you use it, but it can also simplify one or more other areas of code. For example, if you refer to a static variable in N different locations, to check for nil

in the all N or for the risk of failure Often people call a function or use #define

to handle initialization, and if that code is only used once, it might be a penalty that needs to be removed.

+4


a source







All Articles