我跟隨斯坦福ios 7課程(在第三講),其中教師建立一個卡匹配遊戲。有屏幕十二個卡片,他們都迷上高達這個屬性在視圖控制器方法沒有被調用,但沒有錯誤,當我建立
@property (strong, nonatomic) IBOutletCollection(UIButton) NSArray *cardButtons;
,並點擊任何按鈕時,就會觸發這個方法
- (IBAction)touchCardButton:(UIButton *)sender {
NSLog(@"touchCardbutton");
int cardIndex = [self.cardButtons indexOfObject:sender];
[self.game chooseCardAtIndex:cardIndex];
[self updateUI];
}
觸發updateUI中的viewController
- (void)updateUI{
NSLog(@"updateUI");
for (UIButton *cardButton in self.cardButtons){
int index = [self.cardButtons indexOfObject:cardButton];
NSLog(@"index in UpdateUI %d", index);
Card *card = [self.game cardAtIndex:index];
NSLog(@"card in UpdateUI %@", card);
[cardButton setTitle:[self titleForCard:card ]forState:UIControlStateNormal];
[cardButton setBackgroundImage:[self backgroundImageForCard:card] forState:UIControlStateNormal];
cardButton.enabled = !card.isMatched;
}
}
在該updateUi方法中,第二的NSLog語句表示card
爲零。第一條NSLog語句顯示index
沒有問題。那麼爲什麼card
零?我假設這個屬性在視圖控制器中引用的cardMatchGame類中的cardAtIndex方法存在一些問題,它們來自視圖控制器 @property(strong,nonatomic)CardMatchingGame * game;
cardAtIndex
-(Card *)cardAtIndex:(NSInteger)index
{
NSLog(@"cardAtIndex %d", index);
return (index < [self.cards count]) ? self.cards[index] : nil;
}
這NSLog的聲明沒有顯示在控制檯上,所以不會出現任何的事情發生時,我打電話cardAtIndex在updateUI
Card *card = [self.game cardAtIndex:index];
你能解釋爲什麼該方法cardAtIndex可能沒有被調用,當我構建並運行時也沒有錯誤消息?
更新
在視圖控制器,遊戲屬性懶洋洋地實例化這樣
-(CardMatchingGame *)game
{
if (_game) _game = [[CardMatchingGame alloc] initWithCardCount:[self.cardButtons count] usingDeck:self.createDeck];
return _game;
}
記錄'self.game'。我想你會得到'nil',而你忘了將它分配到某個地方。 – Wain
如果您請求的卡片索引高於數組中的元素數量,'cardAtIndex'也將返回零,因此您的數組可能無法正確加載。嘗試在'cardAtIndex'處設置斷點並查看該方法中發生了什麼 – Paulw11
@Wain logging self.game表示它爲NULL。在ViewController的頂部,我設置了這個屬性'@property(strong,nonatomic)CardMatchingGame * game;'我認爲這會讓我調用'self.game'而不需要指定任何東西 – BrainLikeADullPencil