nsarray 释放_NSArray:lastObject是否返回一个自动释放的对象?

bd96500e110b49cbb3cd949968f18be7.png

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)

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.

解决方案

Why not call

[array removeLastObject]

at the end of your function? That's one fewer release/retain. It might make your code more readable/less cluttered.

For the record the 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];

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值