Does removeObject release the object in an NSMutab

2020-06-17 14:35发布

I was wondering when you remove an object using removeObject in an array if that removed object is handled properly. Would the object being removed be released?

4条回答
贪生不怕死
2楼-- · 2020-06-17 15:18

As everybody has said, the object of a NSMutableArray is released after it is removed from the array.

If you don´t want to release the object, retain it just before you call remove object method. In this case, you are responsible for it to release it later:

MyClass *objectToBeRemoved=[myArray objectAtIndex:indexPath.row];
[objectToBeRemoved retain];
[myArray removeObject:objectToBeRemoved];
查看更多
啃猪蹄的小仙女
3楼-- · 2020-06-17 15:24

The NSMutableArray will release it. If that's the last retain on it, it will be deallocated. From the documentation:

Like NSArray, instances of NSMutableArray maintain strong references to their contents. If you do not use garbage collection [Jed: the iPhone does not], when you add an object to an array, the object receives a retain message. When an object is removed from a mutable array, it receives a release message. If there are no further references to the object, this means that the object is deallocated. If your program keeps a reference to such an object, the reference will become invalid unless you send the object a retain message before it’s removed from the array.

See the NSMutableArray documentation. Their example, in fact, refers to removeObjectAtIndex::

id anObject = [[anArray objectAtIndex:0] retain];
[anArray removeObjectAtIndex:0];
[anObject someMessage];
查看更多
三岁会撩人
4楼-- · 2020-06-17 15:24

Yes. Collections retain values they collect when the values are added to the collection, which means that the values are released when they're removed from the collection.

查看更多
三岁会撩人
5楼-- · 2020-06-17 15:31

Yes, when the object is removed from the NSMutableArray, it is released. If its retain count is 0, it will be deallocated (or garbage collected, if you were instead running on OS X with GC enabled).

查看更多
登录 后发表回答