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

标签 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?

最佳答案

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/

相关文章:

iphone - 相机功能在 iPhone 上不起作用

iphone - 在 UIWebView 中禁用 PDF 文件中的超链接

iphone - 我的 iPhone Simulator 3.0 地址簿是空的!

cocoa - QTMovie 在最小化时暂停?

objective-c - 无法从 NSPopUpButton 中删除项目

ios - SiriKit 自定义意图参数和快捷键

iphone - UIPageViewController 错误

ios - UITableView 删除部分 - 标题保持可见

ios - 缩放/动画UIView的一侧变小? -CGAffineTransformMakeScale

objective-c - 如何通过 Cocoa 查找 mac os 中的显示器数量?