static NSDictionary* const letterValues = @{ … } in a method does not compile

后端 未结 4 1510
南方客
南方客 2021-02-05 13:20

In a word game for iPhone:

\"app

I\'m trying to use the following code in my custom view Tile.

4条回答
  •  不要未来只要你来
    2021-02-05 13:46

    You can only set a static variable during initialization with a constant. @{} creates an object, thus not a constant.

    Do this instead:

    - (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,
              };
        });
    
    
        ...
    }
    

    Some other answers here suggest a check for nil instead of dispatch once, but that can cause issues when creating multiple tiles at the same time (via threads). dispatch_once implements the required locking.

提交回复
热议问题