我最近输入了this关于 lastObject
是否返回自动释放对象的争论。我一直认为是这样,而且我从来没有遇到过问题,但是,想想看,大多数时候我都使用这种方法,我的收藏超出了引用,所以,显然,即使它只是一个简单的引用,代码本来可以正常工作。因此,关于返回值的自动释放性质,我似乎是错误的(基于一些SO答案),但是,我试图在Apple的文档中找到有关它的内容,但未能这样做。
Apple 是否记录了 lastObject
是否自动释放了它返回的对象?如果有,它记录在哪里?如果这是真的,他们为什么要这么做?我在上述辩论中得到的答案对我来说毫无意义,集合可以保留并自动释放对象,对吧?这样,该对象在运行循环结束时仍然有效。
最佳答案
即使没有明确记录,lastObject
也可能与 objectAtIndex:
具有相同的行为。 objectAtIndex:
不保留
和自动释放
按照本文档返回的对象:Avoid Causing Deallocation of Objects You’re Using .
When an object is removed from one of the fundamental collection classes, it is sent a release (rather than autorelease) message. If the collection was the only owner of the removed object, the removed object (heisenObject in the example ) is then immediately deallocated.
(强调我的)
考虑同一文档页面中的这个示例:
heisenObject = [array objectAtIndex:n];
[array removeObjectAtIndex:n];
// heisenObject could now be invalid.
就内存管理而言,释放整个数组与删除所有对象相同,因此您不能指望返回的对象在运行循环结束之前保持有效,即使在某些情况下它实际上可能不会被释放。情况(例如文字字符串、单例、对对象的其他引用等)。
关于objective-c - -[NSArray lastObject] 是否记录为返回自动释放的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104615/