NSArray:lastObject是否返回一个自动释放的对象? [英] Does NSArray:lastObject return an autoreleased object?
问题描述
我正在一个iPhone项目,我想从一个NSMutableArray检索一个对象,从数组中删除对象,然后使用它。代码看起来像这样:
I'm working on an iPhone project where I would like to retrieve an object from an NSMutableArray, remove the object from the array and then use it later. The code looks something like this:
NSMutableArray * array;
// fill the array
NSObject * obj = [array lastObject];
[array removeLastObject];
// do something with obj (in the same function)
在被访问的对象上有一个retain。这是安全吗?我想假设这只会工作,如果lastObject自动释放对象,这是一个我不能弄清楚如果它。
array is the only entity with a retain on the object that is being accessed. Is this safe to do? I would assume that this would only work if lastObject autoreleased the object which is something that I can't figure out if it does.
推荐答案
为什么不调用
[array removeLastObject]
在函数的结尾?这是少一个释放/保留。
at the end of your function? That's one fewer release/retain. It might make your code more readable/less cluttered.
对于记录, Apple文档:
与NSArray类似,
NSMutableArray的实例对它们的内容保持强的
引用。如果你
不使用垃圾收集,当
你添加一个对象到数组,
对象接收一个保留消息。当
从一个可变的
数组中删除一个对象时,它接收一个释放消息。
如果没有进一步引用
对象,这意味着对象
被释放。如果你的程序保持
对这样的对象的引用,
引用将变得无效,除非
在从数组中删除之前发送对象一个保留消息
。
例如,如果anObject在从
数组中删除之前不保留
,则下面的第三个语句可能会导致运行时错误:
Like NSArray, instances of NSMutableArray maintain strong references to their contents. If you do not use garbage collection, 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. For example, if anObject is not retained before it is removed from the array, the third statement below could result in a runtime error:
id anObject = [[anArray objectAtIndex:0] retain];
[anArray removeObjectAtIndex:0];
[anObject someMessage];
这篇关于NSArray:lastObject是否返回一个自动释放的对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!