我有几个关于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?
此处相同:您的分配释放了该对象。由于这个没有自动释放(你alloc
自己动手),该对象将立即死亡。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)