0
votes

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

1
Show the implementation of 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.Arkku
added card class implementationsteve
In loadCardNumbers, can you log cards immediately after logging c? Do you see the different cards being added to cards?John Sauer
all cards are printing the same as the last object. i.e. when there are 3 cards all 3 print as "suit 1 rank 3"steve
Generally, everything in C is 0 based... not 1 based. Not a big issue.bbum

1 Answers

0
votes

original Card.h implementation:

int suit;
int rank;
@interface Card : NSObject    

-(id)init;
...

Correct implementation with arkku's advice:

@interface Card : NSObject
{

int suit;
int rank;
}
-(id)init;
...