Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the removeAllObjects method of an NSArray or NSMutableArray release memory?

I need to know if the removeAllObjects method of an NSArray or NSMutableArray releases memory.

If my array has got 10000 elements. Can I use the

[array removeAllObjects];

to release the memory and reload it with other elements? Or it leaks memory?

Thanks

EXAMPLE if the size of my NSMutable array is 20mb with 10.000 elements for example... if I use the removeAllObjects method...will its size be 0mb?

like image 226
Usi Usi Avatar asked Sep 14 '25 06:09

Usi Usi


2 Answers

Yes, it releases all the objects, it doesn't leak. (It doesn't, of course, explicitly deallocate them - they are only deallocated if the only reference to them was held by the array.)

An NS[Mutable]Array is a collection of references to object. Calling -removeAllObjects nils those references. The capacity and memory used by the array itself stay the same. In the case of NSMutableArray, those references can be reused to point to other objects. NSArray lacks the method -removeAllObjects because it's not mutable.

removeAllObjects will be marginally slower for a high number of objects than initWithCapacity. The real performance difference would be having to avoid growing the array when the number of objects reaches the limit.

As others pointed out, the objects are only released if there are no more strong references to them.

like image 22
Jano Avatar answered Sep 15 '25 19:09

Jano