I'm writing a simple iPhone app to display a deck of cards. Every time a button is placed, a new card will be shown without replacement.
Every time my buttonPressed method is called, the NSMutableArray in my deck class holding the cards is reset to null. Using some printf's I've found that the reset occurs right when the button is clicked (i.e. between the last line of the previous buttonclick and the first line of the new button click). Additionally, a new Deck object is not being created.
I don't think any of the lines in touchCardButton are making the deck nil. I can still draw cards at the very last line of touchCardButton. However, I cannot draw them at the very first line. I'm thinking there's something about initializing the deck that I'm missing (why does it lose its value when I'm not doing anything?)
To reiterate, I'm not asking to have my code debugged, as I've already done that. I know the issue lies arises between the last line of touchCardButton and the first line (ostensibly, where nothing occurs). I'm wondering what could cause this to happen, and I'm also including the code as reference.
- (IBAction)touchCardButton:(UIButton *)sender { //buttonClick Code
PlayingCard *displayCard = nil;
if(![self.deck drawRandom])
printf("\nblank1\n");
else printf("\nfull1\n");
displayCard = [self.deck drawRandom];
if(![self.deck drawRandom])
printf("\nblank3\n");
else printf("\nfull3\n");
if (!displayCard) {
if(![self.deck drawRandom])
printf("\nblank4\n");
else printf("\nfull4\n");
printf("null cards");
[sender setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
[sender setTitle:@"" forState:UIControlStateNormal];
}
else{
[sender setBackgroundImage:[UIImage imageNamed:@"front"] forState:UIControlStateNormal];
[sender setTitle:[displayCard contents] forState:UIControlStateNormal];
}
self.flipCount++;
if(![self.deck drawRandom])
printf("\nblank5\n");
else printf("\nfull5\n");
}
Deck Code
- (instancetype) init{
self = [super init];
printf ("remade");
if (self){
for (NSString *curSuit in [PlayingCard validSuits])
for (NSString *curRank in [PlayingCard validRanks]) {
PlayingCard *addedCard = [[PlayingCard alloc] init];
addedCard.rank = curRank;
addedCard.suit = curSuit;//curSuit;
[self addCard: addedCard];
//printf([addedCard.suit UTF8String]);
}
if (self.beenMade)
printf("true");
else
printf("false");
}
self.beenMade = true;
return self;
}
And Draw Card method
- (PlayingCard *) drawRandom {
if(self.cards.count){
printf("swag");
unsigned index = arc4random()%self.cards.count;
PlayingCard *cardDealt = self.cards[index];
[self.cards removeObjectAtIndex: index];
return cardDealt;
}
else
return nil;
}
if(![self.deck drawRandom])
removes a card from the deck, right? So every time you push the button, five cards are removed from the deck. – user3386109