0

2013年冬からiOSの講義(Paul Hegertyによる)を見てきましたが、Matchisimoプログラムでこの2行目のコードが必要な理由に頭を悩ませているようには見えません。コメントアウトするとプログラムがクラッシュしますが、そのままにしておくと問題なく動作します。

[cardButton setTitle:card.contents forState:UIControlStateSelected];

[cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

この行で失敗します:

@autoreleasepool {
    return UIApplicationMain(argc, argv, nil, NSStringFromClass([CardGameAppDelegate class]));
}

2行目がコメントアウトされている場合にエラーが発生します:

'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 47 beyond bounds [0 .. 46]'

カードの内容:

@property (strong, nonatomic) NSString *contents;

UIの更新:

- (void)updateUI
{
    for (UIButton *cardButton in self.cardButtons) {
        Card *card = [self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];

        [cardButton setTitle:card.contents forState:UIControlStateSelected];

        [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

        cardButton.selected = card.isFaceUp;
        cardButton.enabled = !card.isUnPlayable;
    }
}
4

1 に答える 1

3

この行をコメントし[cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];ても、何らかの理由でクラッシュすることはありません。

これは、[self.game cardAtIndex:[self.cardButtons indexOfObject:cardButton]];範囲外のインデックスに関連するクラッシュを引き起こしている行です。基本的に、カードよりも多くの cardButtons がself.gameあります。

これでラップしてクラッシュを防ぐことができますが、余分なボタンが作成される理由について、より深い根本的な問題を探す必要があります。

int buttonIndex = [self.cardButtons indexOfObject:cardButton];
if (self.game.count > buttonIndex) {
    Card *card = [self.game cardAtIndex:buttonIndex];

    [cardButton setTitle:card.contents forState:UIControlStateSelected];

    [cardButton setTitle:card.contents forState:UIControlStateSelected|UIControlStateDisabled];

    cardButton.selected = card.isFaceUp;
    cardButton.enabled = !card.isUnPlayable;
}
于 2013-03-05T16:58:21.040 に答える