Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSMutableArray destruction

I have an array NSMutableArray with happy objects. These objects viciously turn on (leak) me whenever I try to clear the array of all the objects and repopulate it.

It's allocated in the init function like so

self.list = [NSMutableArray array];

The different methods I have used to clear it out include:

self.list = nil;
self.list = [NSMutableArray array];

and

[self.eventList removeAllObjects];

Explicitly allocating and releasing the array doesn't work either. The leak ONLY occurs when I try to reset the list.

Am I missing a step when resetting or is this a different problem?

like image 971
SageAMDP Avatar asked Oct 07 '08 18:10

SageAMDP


1 Answers

How did you create the objects that are leaking? If you did something like this:

- (void)addObjectsToArray {

    [list addObject:[[MyClass alloc] init];

    OtherClass *anotherObject = [[OtherClass alloc] init];
    [list addObject:anotherObject];
}

then you will leak two objects when list is deallocated.

You should replace any such code with:

- (void)addObjectsToArray {

    MyClass *myObject = [[MyClass alloc] init];
    [list addObject:myObject];
    [myObject release];

    OtherClass *anotherObject = [[OtherClass alloc] init];
    [list addObject:anotherObject];
    [anotherObject release];
}

In more detail:

If you follow the first pattern, you've created two objects which, according to the Cocoa memory management rules you own. It's your responsibility to relinquish ownership. If you don't, the object will never be deallocated and you'll see a leak.

You don't see a leak immediately, though, because you pass the objects to the array, which also takes ownership of them. The leak will only be recognised when you remove the objects from the array or when the array itself is deallocated. When either of those events occurs, the array relinquishes ownership of the objects and they'll be left "live" in your application, but you won't have any references to them.

like image 173
mmalc Avatar answered Oct 30 '22 01:10

mmalc