I have a method to generate a Deck object (NSObject subclass with an NSMutableArray property) and it populates the array with Card objects (UIView subclass with some integer and one NSString property). When I ask for a Deck I check to see if one already exists (I think) and if so, release it before getting a new one.
The code from my viewcontroller...
#import "FlashTestViewController.h"
@implementation FlashTestViewController
- (IBAction)generateDeck {
if (aDeck != nil) {
[aDeck release];
}
aDeck = [[Deck alloc] initDeckWithOperator:@"+"];
}
- (IBAction)generateCard {
if (aCard != nil) {
[aCard fadeAway];
}
aCard = [aDeck newCardFromDeck];
[self.view addSubview:aCard];
}
- (void)fadeAway {
[aCard removeFromSuperview];
[aCard release];
}
@end
The Deck class is as follows...
#import <Foundation/Foundation.h>
#import "Card.h"
@class Deck;
@interface Deck : NSObject {
NSMutableArray* cards;
}
@property(nonatomic, retain) NSMutableArray* cards;
- (id)initDeckWithOperator: (NSString*)mathOper;
- (id)newCardFromDeck;
@end
- (id)initDeckWithOperator: (NSString*)mathOper {
if (cards != nil) {
[cards release];
}
cards = [[NSMutableArray alloc] init];
for (int i=0; i<11; i++) {
for (int j=0; j<11; j++) {
int xPos = (random() % 220) + 10;
int yPos = (random() % 360) + 10;
Card* aCard = [[Card alloc] initWithFrame:CGRectMake(xPos, yPos, 60, 80)];
aCard.upperOperand = i;
aCard.lowerOperand = j;
aCard.theOperator = mathOper;
aCard.theResult = i + j;
UITextView* upperTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 5, 50, 20)];
NSString* upperOper = [[NSString alloc] initWithFormat:@" %d", i];
upperTextView.text = upperOper;
[aCard addSubview:upperTextView];
[upperTextView release];
[upperOper release];
UITextView* middleTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 30, 50, 20)];
NSString* middleOper = [[NSString alloc] initWithFormat:@"%@ %d", mathOper, j];
middleTextView.text = middleOper;
[aCard addSubview:middleTextView];
[middleTextView release];
[middleOper release];
UITextView* lowerTextView = [[UITextView alloc] initWithFrame:CGRectMake(5, 55, 50, 20)];
NSString* lowerOper = [[NSString alloc] initWithFormat:@" %d", j+i];
lowerTextView.text = lowerOper;
[aCard addSubview:lowerTextView];
[lowerTextView release];
[lowerOper release];
[cards addObject: aCard];
[aCard release];
}
}
return self;
}
- (id)newCardFromDeck {
int index = random() % [cards count];
Card* selectedCard = [[cards objectAtIndex:index] retain];
[cards removeObjectAtIndex:index];
return selectedCard;
}
@end
I do the same thing when I ask for a new card from the newCardFromDeck method and it works. Any suggestions?
Thanks!