0

I have tried to search for similar problems, but not found any good solutions. So I hope someone can help me.

Basically I have a leak in this method that populates an Array with Card objects (the tempArray is created and populated above this loop):

for(int i = 0; i < numberOfCards; i += 2) {
    int randomNumber = (arc4random() % [tempArray count]);
    NSNumber *number = [tempArray objectAtIndex:randomNumber];
    [tempArray removeObject:number];

    Card *card1 = [[Card alloc] initWithCategory:category andNumber:[number intValue]];
    Card *card2 = [[Card alloc] initWithCategory:category andNumber:[number intValue]];

    [number release];

    [cards addObject:card1];
    [cards addObject:card2];
}

The method does contain a little more logic, but I am pretty sure this loop contains the leak. When I run it with Instruments I see that the Card objects does not get released. In the dealloc method I do release the array, I thought this would also release the objects inside the Array?

-(void) dealloc {
    [cards release];

    [super dealloc];
}

I have tried autorelease on card1 and card2, tried to make them class variables. But nothing seems to help. Either I have the leak or if I try to add a release on the card1 or card2 the application crashes. Anyone have an idea what is wrong here?

1
  • N.B. you should not release number since you do not own it. Commented Jul 29, 2011 at 17:57

1 Answer 1

2

You need to release each Card object after you have added them to cards. When adding them to cards the retain count of each object automatically increases. Therefore add:

[card1 release];
[card2 release];

after

[cards addObject:card1];
[cards addObject:card2];
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that makes sense. However, it does crash now in the dealloc method, when I call [cards release]; Not sure why.
Look for all places in code where you either say [cards retain];, cards = [[NSAMutable alloc] ..]; and then all places where you say [cards release]; They should cancel each other out.
Finally I got it working, thanks for the help. One thing I dont understand thought, in the card object had two properties. When I changed the settings from image=... and text=... to self.image= and self.text= it worked. Do you know why?
Yes, when you use self.property = .., you are using the setter function, in there it automatically retains the value you are setting. However, if you are only saying property = .. the getter is not called and you have to retain yourself. You can try this by removing self. and instead add image = [.. retain];

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.