views:

207

answers:

2

Hi

I currently try to fill and NSMutableArray with something like this:

deck = [[NSMutableArray alloc] initWithCapacity:52]; 
for (int suit = 0; suit <= 3; suit++) {
  for (int value = 1; value <= 13; value++) {
    ANormalCard *card = [[ANormalCard alloc] initWithSuit:suit value:value];
    [deck addObject:card];
    [card autorelease];
  }
}

Now the problem is when I go over the array, only the last object I create is 52x in the array. Any idea what I am doing wrong ?


Edit:

the -initWithSuit looks like this:

- (id) initWithSuit:(int)suit value:(int)val {
    if ((self = [super init])) {
        theSuit = suit;
        theValue = val;
    }
    return self;
}

I'm using NSEnumerator * enumerator = [deck objectEnumerator]; and a while loop to iterate over the array.

+2  A: 

This code snippet looks perfectly fine. The problem is likely in your -initWithSuit:value: method — I'd check whether you're accidentally initializing the cards incorrectly.


Edit: The init method just posted by the asker looks fine as well. What is the exact output you're seeing that leads you to believe that only the last object has been added 52 times? How exactly are you examining the array? (Your comment says you're using an NSEnumerator, but can you edit your question to include the snippet you're using for that?

Quinn Taylor
the -initWithSuit looks like this :-(id)initWithSuit:(int) suit value:(int)val{if ((self=[super init]) ) { theSuit = suit; theValue = val;}return self;}
eemceebee
I added it to your question.
Quinn Taylor
A: 

I'd be curious to see the code where you examine the array.

peterb
just using this : NSEnumerator * enumerator = [deck objectEnumerator]; and while over it
eemceebee
Why not `for (ANormalCard *card in deck) { [card whatever]; } `?
jbrennan
I agree. I suspect the code the enumerates over the array isn't quite right or you are mis-interpretting the results. Are you looking at the results in a debugger or printing them to the console or something?
Marplesoft
Well, what ever method /code you use, all I get is the same card at the end. Even with [deck objectAtIndex:30]; gives the same value as [deck objectAtIndex:44];
eemceebee
Please post a small code listing that produces the results. It looks like everybody here believe that there's something wrong with the init method or the enumeration.
Marplesoft