When do these objects get released under ARC?

南笙酒味 提交于 2019-12-21 20:18:36

问题


I have a few questions about ARC (automatic reference counting):

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:


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?

Yes, because they're the same object. Only the type changes; it is still the same reference to the same object.

That said, expecting an object to continue to “be available for ‘a while’” after you release your last ownership of it is fragile. If you intend to keep using that object, own it for at least that long. Release it when you're done with it, and no sooner.

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?

Yes and no.

An assignment to a strong variable (and variables are implicitly strong unless otherwise specified) releases the previous value immediately and retains the new value. Each assignment of an NSURL object caused the object to be retained; each assignment of nil caused the previously-held object to be released.

However, in both cases, the URL object may have been autoreleased by fileURLWithPath:. That autorelease, as always, comes due no sooner than the end of the autorelease pool, so the object may continue to live until then. That generally isn't a problem, but it can occasionally pop up if you're making a lot of objects (e.g., in a tight loop).

As far as you're concerned, yes, each assignment of nil releases the object that resided there before, fulfilling and ending your responsibility to that ownership.

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

Same here: Your assignment releases the object. And since there's no autorelease in this one (you allocked it yourself), the object will die immediately.



来源:https://stackoverflow.com/questions/8682128/when-do-these-objects-get-released-under-arc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!