开发者

Objective C: Initializing static variable with static method call

开发者 https://www.devze.com 2022-12-30 02:30 出处:网络
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).

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 th开发者_如何学编程at 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).


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.


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=[ ... ] ;
    }
    
0

精彩评论

暂无评论...
验证码 换一张
取 消