1

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.

4
  • make sure that initWithSuit:value: is not returning always the same object. Commented Aug 18, 2009 at 20:45
  • I don't think I understood the question - what is the problem with the last object? Commented Aug 18, 2009 at 20:46
  • 2
    That code looks fine. How does your actual code differ? And can you post the code for initWithSuit:value: ? Commented Aug 18, 2009 at 20:46
  • At this point, I don't think the question is answerable without seeing the complete source code. Can you create a minimal version that still exhibits the behaviour? Commented Aug 19, 2009 at 15:04

1 Answer 1

2

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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

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.