简体   繁体   中英

Memory leak, nsmutablearray and custom object

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?

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM