【发布时间】:2014-04-27 08:58:08
【问题描述】:
我正在尝试在我的自定义视图Tile.m 中使用以下代码:
- (void)awakeFromNib
{
[super awakeFromNib];
static NSDictionary* const letterValues = @{
@"A": @1,
@"B": @4,
@"C": @4,
// ...
@"X": @8,
@"Y": @3,
@"Z": @10,
};
NSString* randomLetter = [kLetters substringWithRange:[kLetters rangeOfComposedCharacterSequenceAtIndex:arc4random_uniform(kLetters.length)]];
int letterValue = [letterValues[randomLetter] integerValue];
_smallLetter.text = _bigLetter.text = randomLetter;
_smallValue.text = _bigValue.text = [NSString stringWithFormat:@"%d", letterValue];
}
不幸的是,这给了我编译错误Initializer element is not a compile-time constant,我必须删除 static 关键字才能在 Xcode 中编译我的应用程序(此处为 fullscreen):
我想我正确地初始化了NSDictionary - 使用新的Objective-C Literals 语法。
但是为什么我不能在这里使用static?
我认为在这里确保我的letterValues 常量只设置一次是合适的吗?
【问题讨论】:
-
把它移出课堂
-
将其从类中移出会导致相同的编译时错误
-
@Btw.,该代码是有效的并且在Objective-C++中工作:-)
-
哪个代码有效(我的问题中的代码在 Xcode 5.1 中无法编译)以及 Objective-C++ 是什么意思?
-
@AlexanderFarber:请参阅stackoverflow.com/questions/3684112/what-is-objective-c - Objective-C++ 是 Objective-C 与 C++ 的“组合”(并且文档很少)。 Objective-C++ 文件的扩展名为 .mm。如果您将文件重命名为“Tile.mm”,您的代码应该可以编译,因为 C++ 对静态初始化程序有不同的规则。 - 但这只是作为一个评论,而不是作为 the 解决方案。 - 你也可以看看stackoverflow.com/questions/21365532/…,这是一个不同的问题,有相似的答案。
标签: ios objective-c static nsdictionary constants