views:

88

answers:

2

I am having a memory leak issue with the following code. As much as I can tell I don't see why the problem persists but it still does not release when called. I am detecting the problem in instruments and the following code is keeping its "cards" classes alive even when it should had released them. Any help welcome.

... 
...
-(id)initDeckWithCardsPicked: (NSMutableArray*)cardsPicked andColors:(NSMutableArray*)cardColors
    {
        self = [self init];
        if (self != nil) {
            int count = [cardsPicked count];
            for (int i=0; i<count; i++) {
                int cardNum = [[cardsPicked objectAtIndex:i] integerValue];
                Card * card = [[MemoryCard alloc] initWithSerialNumber:cardNum position: CGPointZero color:[cardColors objectAtIndex:i]];
                [_cards addObject: card];
                [card release];
            }
        }
        return self;    
        }

- (id) init
{
    self = [super init];
    if (self != nil) {
        self.bounds = (CGRect){{0,0},[Card cardSize]};
        self.cornerRadius = 8;
        self.backgroundColor = kAlmostInvisibleWhiteColor;
        self.borderColor = kHighlightColor;
            self.cards = [NSMutableArray array];
        }
          return self;
}
...
...
A: 

When you add a Card to the _cards NSMutableArray using addObject, it is sent a retain message. Thus, as long as you keep _cards in memory, a pointer will also be kept for each of it's constituents. As long as your dealloc releases the array, or you do so elsewhere, you shoul dbe fine with what you have posted here (assuming your initWithSerialNumber method returns a retained object).

coneybeare
I did release the array via dealloc... [_cards release];[super dealloc]; ... but from what I understand the class is referenced from somewhere else and does not allow the release ?
franz
+1  A: 

Without looking at the rest of your code, its hard to know where the problem is, but have you tried using the static analyzer in xcode? Its can be invaluable for finding memory leaks.

To use it, select 'Build and Analyze' from the Build menu. Further details are on Apple's dev website.

Tim Lewis