Does removeObject release the object in an NSMutableArray of objects?

前端 未结 4 978
春和景丽
春和景丽 2021-02-16 00:29

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条回答
  •  生来不讨喜
    2021-02-16 00:43

    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];
    

提交回复
热议问题