I'm trying to populate my nsmutablearray with a deck of playing cards. The card object has a suit and rank. The code is as follows:
-(void)loadCardNumbers {
if(numDecks > 0)
{
//for each deck
for(int i = 1; i<= numDecks; i++)
{
//for each suit
for(int j = 1; j <= 4; j++)
{
//for each card 1-ace
for(int k = 1; k <= 13; k++)
{
//create card and add to shoe
Card *c = [[Card alloc]initWithSuit:j AndRank:k];
NSLog(@"%@", c);
[cards addObject:c];
}
}
}
}
And the card class:
@implementation Card
//return ace of spades, arbitrary card.
-(id)init
{
return [self initWithSuit:DIAMONDS AndRank:ACE];
}
-(id)initWithSuit:(int)s AndRank:(int)r
{
self = [super init];
if(self)
{
suit = s;
rank = r;
}
return self;
}
-(int)suit
{
return suit;
}
-(int)rank
{
return rank;
}
-(NSString *) description
{
return [NSString stringWithFormat:@"CARD WITH SUIT %d AND RANK %d", suit, rank];
}
@end
For some reason, the NSLog looks correct in the method (correctly printing 1...4 for suit and 1...13 for rank). However, when I call description on the array after the method completes, all of the objects print "suit 4 rank 13", meaning they are all pointing to the last object I added. Any ideas on how to fix this?
edit: as arkku pointed out, my ivars were declared as class variables. Forgot to include curly brackets around my ivars in Card.h
Card
, especially how you define and initialize the suit and rank… my guess is that the problem is accidentally sharing the suit and rank variables across all Cards rather than each having its own. – ArkkuloadCardNumbers
, can you logcards
immediately after loggingc
? Do you see the different cards being added tocards
? – John Sauer