问题描述
我有这段代码:
- (NSString *) calculate: (uint) position {
static NSArray * localArray = [NSArray arrayWithArray: self.container.objects ];
// some un related code
return obj;
}
编译器抱怨说:Initializer元素不是编译时常量 。它发生在我向localArray添加static时。但为什么?
The compiler complains saying: "Initializer element is not a compile-time constant". It happened when I added "static" to localArray. But why?
推荐答案
因为 [NSArray arrayWithArray:self.container.objects]
不是编译时常量,它是必须在运行时计算的表达式。在C和Objective-C中, static
函数内部的变量必须使用编译时常量进行初始化,而C ++和Objective-C ++则更宽松,允许非编译时常量。
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.
将代码编译为Objective-C ++,或者将其重构为以下内容:
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 ];
这与编译器为<$ c $引发的代码非常相似c> static 变量用非编译时常量初始化(实际上,它会使用第二个全局标志来指示值是否已初始化,而不是使用像<$ c $这样的标记值c> nil here;在这种情况下,我们假设 localArray
永远不会 nil
)。如果需要,可以查看编译器的反汇编。
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.
这篇关于“Initializer元素不是编译时常量”。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!