Fry
Fry

Reputation: 6275

Remove objects from NSArray

I have a project with ARC.

I have an NSArray whit some object inside. At certain point I need to change the object in the array.

Whit a NSMutableArray I'll do :

[array removeAllObjects];

and I'm sure that this method release all object contained in the array. But with an NSArray I can't do that! So, my question is: if I set array to nil and then re-initialize it, the old object contained in the array are really released from memory ?

array = nil;
array = [[NSArray alloc] initWithArray:newArray];

Or I need to use NSMutableArray ?

Upvotes: 15

Views: 35042

Answers (3)

Andreas Ley
Andreas Ley

Reputation: 9335

You can just do this:

array = newArray;

This will cause array to be released. When this NSArray gets deallocated, all contained objects will be released, too.

Upvotes: 13

rob mayoff
rob mayoff

Reputation: 385510

The old array will be deallocated when there are no more strong references to it. If you had the only strong reference to it, then when you set array to something else, it will be deallocated immediately.

When the old array is deallocated, it will release all of the objects it contains. If there are no other strong references to those objects, they will also be deallocated immediately.

You don't have to set array = nil before setting it to the new array.

Upvotes: 4

Techie Manoj
Techie Manoj

Reputation: 432

I would suggest NSMutableArray because there would not be overhead of allocation and deallocation again

Upvotes: 1

Related Questions