0

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

8
  • 4
    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. Commented Mar 26, 2013 at 2:00
  • added card class implementation Commented Mar 26, 2013 at 2:07
  • In loadCardNumbers, can you log cards immediately after logging c? Do you see the different cards being added to cards? Commented Mar 26, 2013 at 2:10
  • 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" Commented Mar 26, 2013 at 2:20
  • Generally, everything in C is 0 based... not 1 based. Not a big issue. Commented Mar 26, 2013 at 2:28

1 Answer 1

0

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;
...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.