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

后端 未结 4 1451
南方客
南方客 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:31

    You can use static, but the assignment can't be made on the same line. Try this:

    - (void)awakeFromNib {
        [super awakeFromNib];
    
        static NSDictionary* letterValues = nil;
        if (!letterValues) {
            letterValues = @{@"A": @1,
                             @"B": @4,
                             @"C": @4,
                             // ...
                             @"X": @8,
                             @"Y": @3,
                             @"Z": @10};
        }
        ...
    }
    

    The reason is that the @{ : } syntax is translated by the compiler into an Objective-C method ([[NSPlaceholderDictionary alloc] initWithObjects:forKeys:count:]), which cannot be resolved at compile-time.

提交回复
热议问题