我正在做一个 iPhone 项目,我想从 NSMutableArray 中检索一个对象,从数组中删除该对象,然后在以后使用它。代码看起来像这样:
NSMutableArray * array;
// fill the array
NSObject * obj = [array lastObject];
[array removeLastObject];
// do something with obj (in the same function)
array 是唯一在被访问的对象上保留的实体。这样做安全吗?我假设这只有在 lastObject 自动释放对象时才有效,但我无法确定它是否有效。
最佳答案
为什么不打电话
[array removeLastObject]
在你的函数结束时?这是少一个发布/保留。它可能会使您的代码更具可读性/更简洁。
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];
关于iphone - NSArray 是否为 :lastObject return an autoreleased object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2893888/