2014-03-25 49 views
0

我跟隨斯坦福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; 
} 
+2

記錄'self.game'。我想你會得到'nil',而你忘了將它分配到某個地方。 – Wain

+0

如果您請求的卡片索引高於數組中的元素數量,'cardAtIndex'也將返回零,因此您的數組可能無法正確加載。嘗試在'cardAtIndex'處設置斷點並查看該方法中發生了什麼 – Paulw11

+0

@Wain logging self.game表示它爲NULL。在ViewController的頂部,我設置了這個屬性'@property(strong,nonatomic)CardMatchingGame * game;'我認爲這會讓我調用'self.game'而不需要指定任何東西 – BrainLikeADullPencil

回答

3

self.game引用nil所以沒有調用。由於調用nil被定義爲不執行任何操作,因此不會引發警告/錯誤。

您的問題將出現在您的訪問方法的邏輯問題,它應該是幹:

- (CardMatchingGame *)game 
{ 
    if (!_game) 
     _game = [[CardMatchingGame alloc] initWithCardCount:[self.cardButtons count] usingDeck:self.createDeck]; 

    return _game; 
} 

注加的!

它通常最好不要快捷方式,並使用if (!something)但以明確並使用if (something == nil),因爲它更清晰,更快地瞭解發生了什麼。