我一直在观看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;
}
}
答案 0 :(得分: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;
}