ios “初始化元素不是编译时常量”为什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12304740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
"Initializer element is not a compile-time constant" why?
提问by subzero
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?
编译器抱怨说:“Initializer 元素不是编译时常量”。当我向 localArray 添加“静态”时发生了这种情况。但为什么?
回答by Adam Rosenfield
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-timeconstants, whereas C++ and Objective-C++ are more lenient and allow non-compile-time constants.
因为[NSArray arrayWithArray: self.container.objects ]
它不是编译时常量,所以它是一个必须在运行时计算的表达式。在 C 和 Objective-C 中,static
函数内部的变量必须用编译时常量初始化,而 C++ 和 Objective-C++ 更宽松,允许非编译时常量。
Either compile your code as Objective-C++, or refactor it into something like this:
要么将您的代码编译为 Objective-C++,要么将其重构为如下所示:
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.
这与编译器在后台为static
使用非编译时常量初始化的变量生成的代码非常相似(实际上,它将使用第二个全局标志来指示该值是否已初始化,而不是使用像nil
这里的哨兵值;在这种情况下,我们假设localArray
永远不会nil
)。如果需要,您可以查看编译器的反汇编。
回答by Dirty Henry
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.
第一条指令将在您的应用程序生命周期中执行一次。每次调用calculate: 方法时都会执行第二条指令。
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.
然而,请注意一个事实,如果使用不当,使用静态变量会导致错误行为,因此如果您对这些感到不安,您可能不应该使用它们。