ios - 方法中的 static NSDictionary* const letterValues = @{ ..... } 无法编译

标签 ios objective-c static nsdictionary constants

a word game for iPhone 中:

app screenshot

我正在尝试在我的自定义 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 ):

Xcode screenshot

我想我正确地初始化了 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/

相关文章:

c# - 使用静态方法的充分理由?

objective-c - 在基于 NSTableView 的 View 中处理自定义选择样式

ios - 如何将单个字符转换为 NSString?

java - 静态类中的列表会生成警告,其他数据类型不会

IOS:这是从服务器下载大尺寸文件的最佳方式

iphone - 我可以在 ios 中更改 Google AdMob Ads 的导航栏位置吗?

javascript - react 反模式?

ios - 为苹果 map 捕捉道路

iphone - AVAudioPlayer是否可以循环播放大型音频文件而没有听得见的间隙?

ios - 无法在 swift 3/FBSDK 4.17 中正确检索 FBSDKAccessToken 当前 token