Home > DeveloperSection > Forums > NSMutableArray destruction
Jayne Spooner
Jayne Spooner

Total Post:21

Points:147
Posted on    August-23-2015 11:43 PM

 iPhone iPhone  Ios  Objective C 
Ratings:


 1 Reply(s)
 423  View(s)
Rate this:

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?



Tarun Kumar

Total Post:210

Points:1614
Posted on    August-24-2015 11:34 PM

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.


Don't want to miss updates? Please click the below button!

Follow MindStick