gpt4 book ai didi

objective-c - 这些对象什么时候在 ARC 下被释放?

转载 作者:搜寻专家 更新时间:2023-10-30 20:03:43 24 4
gpt4 key购买 nike

我有几个关于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?

最佳答案

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?

此处相同:您的分配释放对象。由于这个对象没有自动释放(您自己分配),该对象将立即消亡。

关于objective-c - 这些对象什么时候在 ARC 下被释放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8682128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com