我正在尝试在我的自定义 View 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
常量只设置一次是合适的吗?
最佳答案
您只能在初始化期间使用常量设置静态变量。 @{} 创建一个对象,因此不是常量。
改为这样做:
- (void)awakeFromNib
{
[super awakeFromNib];
static NSDictionary* letterValues = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
letterValues = @{
@"A": @1,
@"B": @4,
@"C": @4,
// ...
@"X": @8,
@"Y": @3,
@"Z": @10,
};
});
...
}
这里的一些其他答案建议检查 nil 而不是一次分派(dispatch),但这可能会在同时创建多个图 block 时(通过线程)导致问题。 dispatch_once 实现所需的锁定。
关于ios - 方法中的 static NSDictionary* const letterValues = @{ ..... } 无法编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22534251/