Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 716
Fry Avatar asked Oct 29 '12 16:10

Fry


3 Answers

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.

like image 135
Andreas Ley Avatar answered Nov 04 '22 05:11

Andreas Ley


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.

like image 45
rob mayoff Avatar answered Nov 04 '22 04:11

rob mayoff


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

like image 1
Techie Manoj Avatar answered Nov 04 '22 04:11

Techie Manoj