I am new to cocoa and new to this forum so forgive me if I seem rather confused. I am working on a simple card game. I have a function in my viewController class that is intended to populate an NSMutableArray with objects corresponding to a class I created to represent each card (deck.m). I use a 'deck' object variable to create each card and then store it in the array. The problem is that each time I use addObject to add the new card to the array all of the objects in the array are changed to the new object being added. I think this is because the deck object used to create the new card is recycled. It appears that each entry in the array is pointing to this one deck variable. My question is, what can I do differently to prevent all the objects in the array from changing? Here is the function in question:
Code:
- (NSMutableArray *)stackTheDeck {
deck *currentCard = [[deck alloc] init];
NSMutableArray *currentDeck = [[NSMutableArray alloc] init];
//NSMutableArray *currentDeck = [NSMutableArray arrayWithCapacity:0];
int i = 0;
for(i = 1; i < 53; i++) {
//Set the state of each card
[currentCard setPlayed:[NSString stringWithFormat:@"false"]];
//Set the card value
if((i % 13) == 10) {
[currentCard setCard:[NSString stringWithFormat:@"J"]];
}
else if ((i % 13) == 11) {
[currentCard setCard:[NSString stringWithFormat:@"Q"]];
}
else if ((i % 13) == 12) {
[currentCard setCard:[NSString stringWithFormat:@"K"]];
}
else if ((i % 13) == 0) {
[currentCard setCard:[NSString stringWithFormat:@"A"]];
}
else {
[currentCard setCard:[NSString stringWithFormat:@"%d", (i%13)]];
}
//Set the suite for the card
switch (i/13){
case 0:
[currentCard setSuite:[NSString stringWithFormat:@"diamond"]];
break;
case 1:
[currentCard setSuite:[NSString stringWithFormat:@"heart"]];
break;
case 2:
[currentCard setSuite:[NSString stringWithFormat:@"spade"]];
break;
case 3:
[currentCard setSuite:[NSString stringWithFormat:@"club"]];
break;
default:
break;
}
//[decks insertObject:currentCard atIndex:(i-1)]; //Add the card to the deck
[currentDeck addObject:currentCard]; //Add the card to the deck
cardLabel.text = [NSString stringWithFormat:@"%@ - %@ - %@",[currentCard card], [currentCard suite], [currentCard played]];
}
[currentCard release];
NSLog([NSString stringWithFormat:@"currentDeck contains %d records.",[currentDeck count]]);
return [currentDeck autorelease];
}
Thanks for looking.