eemceebee
eemceebee

Reputation: 2666

Question about NSMutableArray

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.

Upvotes: 1

Views: 387

Answers (1)

Quinn Taylor
Quinn Taylor

Reputation: 44769

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?

Upvotes: 2

Related Questions