我有一段代码返回如下类型的对象Card
:
-(Card*) drawRandomCard {
if ([self.cards count]) {
unsigned index = arc4random() % self.cards.count;
Card *randomCard = self.cards[index];
[self.cards removeObjectAtIndex:index];
NSLog(@"%@", randomCard.description); **//returns a description and not null**
return randomCard;
} else {
NSLog(@"nil");
return nil;
}
}
当我在其他功能中使用它时,这实际上工作正常,但是下面这个有问题:
- (IBAction)addCards:(UIButton *)sender {
int numberOfCardsToAdd = EXTRA_CARDS_NUMBER;
if ([[self.collectionView visibleCells] count] == 0) {
numberOfCardsToAdd = self.startingCardCount;
}
for (int i = 0; i < numberOfCardsToAdd; i++) {
if (!self.game.deck.isEmpty){
Card *cardToAdd = [self.game.deck drawRandomCard];
NSLog(@"%@", cardToAdd.description); **// gives (null)**
if (cardToAdd) { **// this does not get called**
// do stuff with cardToAdd
}
}
}
[self.collectionView reloadData];
}
因此,由于某种原因,当使用上述方法调用时,似乎 mydrawRandomCard
不起作用。有谁知道如何解决这一问题?
非常感谢!
deck
编辑:我用于初始化具有属性的游戏对象的方法:
- (id) initWithNumberOfCards: (int) numberOfCards withDeck: (SetsPlayingDeck *) deck {
self = [self init];
self.score = 0;
_deck = deck;
_cards = [[NSMutableArray alloc] initWithCapacity:numberOfCards];
for (int i = 0; i < numberOfCards; i++) {
[_cards addObject: [_deck drawRandomCard]];
}
return self;
}
这个方法在程序开始时被调用。
编辑#2:
下面是初始化游戏对象的代码,以及作为其属性的甲板对象:
- (SetsGame *) game {
if (!_game) {
SetsPlayingDeck *deck = [[SetsPlayingDeck alloc] init];
_game = [[SetsGame alloc] initWithCardCount:self.startingCardCount usingDeck:deck];
}
NSLog(@"%@", _game.deck.description); **// this returns null!!**
return _game;
}