iphone - NSArray 是否为 :lastObject return an autoreleased object?

标签 iphone objective-c cocoa

我正在做一个 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]

在你的函数结束时?这是少一个发布/保留。它可能会使您的代码更具可读性/更简洁。

备案Apple documentation :

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/

相关文章:

iphone - 如何获取 iOS6 可用的 SSID 列表

objective-c - 使用 valueForKeyPath 获取数组元素

ios - 如何将字符组合作为常量命令放入 iOS 框架

objective-c - OSX如何具有相同宽度的三个控件(文本框或弹出框或组合框)?

objective-c - 将文本拆分为单词、数字和标点符号

iPhone App基础SDK和iOS部署目标

iphone - 如何在 iPhone 上获取用户的电子邮件地址(经过许可)?

ios - AppClip 和任何其他目标从版本 0.69.6 到 0.70.2 出现 "[AppDelegate window]: unrecognized selector sent to instance"错误

objective-c - 像 iTunes 11 一样绘制 NSTableView 交替行

iphone - UIView 动画仅工作一次