Ben
Ben

Reputation: 33

Memory Leak with NSMutableArray

I am trying to set up a multi-dimensional NSMutableArray. I am initially setting all position to a [NSNumber numberWithInt:0] then replacing the object with another [NSNumber numberWithInt:4] (for example). When I am done I would like to rebuild the array. I am correct in saying [array release]? Will that release all the NSNumber objects? Or do I need to do more advance memory management, like set all objects to nil first?

Upvotes: 3

Views: 87

Answers (3)

Tommy
Tommy

Reputation: 100622

Philosophically, you shouldn't know or care what the NSArray does with respect to retain and release. The extent of your contract with it is that addObject:/etc will put an object into the array and objectAtIndex:/etc will subsequently return the same objects. At most you need to consider whether you need to continue owning an object after putting it into an array, entirely according to your own requirements. NSArray is entirely responsible for its own memory management.

In the case of NSArray, how it manages retains and releases internally is well known and your literal question is already answered by Noah and Joe. But you should never, ever rely on another object having a specific implementation.

Upvotes: 1

Joe
Joe

Reputation: 57179

Your array will properly retain and release your NSNumbers as you add/replace and remove objects, as well as when you release the array holding the items. So yes you are correct since you are using the NSNumbers convenience constructor which will return an autoreleased object.

Upvotes: 2

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

You can either release the array and recreate it or—slightly more efficiently—just call the array’s -removeAllObjects. The NSNumber objects you’re populating it with are autoreleased, so the array, by taking ownership of them when you add them to it, also assumes responsibility for releasing them when it itself gets released or has its contents removed.

Upvotes: 2

Related Questions