Does the removeAllObjects method of an NSArray or

2019-05-10 18:53发布

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?

3条回答
地球回转人心会变
2楼-- · 2019-05-10 19:24

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.

查看更多
三岁会撩人
3楼-- · 2019-05-10 19:39

No it does not leak objects. It is the same as removing every object individually except it is more convenient and faster.

查看更多
SAY GOODBYE
4楼-- · 2019-05-10 19:45

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.)

查看更多
登录 后发表回答