这些对象何时在ARC下发布?

时间:2011-12-30 17:25:07

标签: objective-c cocoa-touch cocoa automatic-ref-counting core-foundation

我有几个关于ARC(自动引用计数)的问题:

CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath];
//Question 1: Here, I would expect the NSURL object to be autoreleased and
//therefore the CFURLRef will also be available for “a while.” Is this correct?

url = NULL;
//Question 2: Will this cause the NSURL to be released immediately?

NSURL *url = [NSURL fileURLWithPath:appPath];
url = nil;
//Question 3: Does the “url = nil” result in an immediate release of the NSURL?

NSURL *url = [[NSURL alloc] initWithString:@"/something"];
url = nil;
//Question 4: What about this?

1 个答案:

答案 0 :(得分:5)

CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:appPath];
//Question 1: Here, I would expect the NSURL object to be autoreleased and
//therefore the CFURLRef will also be available for “a while.” Is this correct?

是的,因为它们是同一个对象。只有类型改变;它仍然是对同一个对象的相同引用。

那就是说,在你释放你的最后一个所有权之后,期望一个对象继续“可用'一段时间'”是脆弱的。如果您打算继续使用该对象,请至少拥有该对象。当你完成它之后立即释放它。

url = NULL;
//Question 2: Will this cause the NSURL to be released immediately?

NSURL *url = [NSURL fileURLWithPath:appPath];
url = nil;
//Question 3: Does the “url = nil” result in an immediate release of the NSURL?

是和否。

对强变量的赋值(除非另有说明,否则变量隐式强)会立即释放先前的值并保留新值。 NSURL对象的每个赋值都会导致保留对象; nil的每个分配都导致先前持有的对象被释放。

但是,在这两种情况下,URL对象可能已由fileURLWithPath:自动释放。与往常一样,自动释放是在自动释放池结束之前到期的,因此对象可能会继续存在直到那时。这通常不是问题,但如果您制作了大量对象(例如,在紧密循环中),它偶尔会弹出。

就您而言,是的,nil的每项任务都会释放之前居住的对象,履行并终止您对该所有权的责任。

NSURL *url = [[NSURL alloc] initWithString:@"/something"];
url = nil;
//Question 4: What about this?

相同:您的作业释放了对象。由于这个中没有自动释放(你自己alloc),物体会立即死亡。