0

从 2013 年冬季开始,我一直在观看 iOS 讲座(由 Paul Hegerty 撰写),我似乎无法理解为什么在 Matchisimo 程序中需要第二行代码。如果我把它注释掉,程序就会崩溃,但如果我把它留在里面,它就可以正常工作。

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

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

在这一行失败:

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

如果第二行被注释掉,则会出现错误:

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

卡片内容:

@property (strong, nonatomic) NSString *contents;

更新用户界面:

- (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 回答