简体   繁体   中英

Does this objective-c code cause memory leak?

Compare the following 2 snippets:

sample 1:

[[UIApplication shareApplication] openURL: [NSURL URLWithString:@"http://stackoverflow.com"]]

and sample 2:

NSURL *url = [[NSUrl URLWithString:@"http://stackoverflow.com"];
[[UIApplication shareApplication] openURL: url];
[url release];

Does sample 1 cause memory leak? is [url release] in sample 2 redundant?

If memory leak does happen, how bad is it?

Sample 1 does not cause a memory leak and is the general way to do it. The NSURL object is autoreleased, and thus you're not supposed to release it yourself (as you do in sample 2).

Sample 1 is perfectly fine, as was already described above. However, sample 2 should actually result in a crash. -URLWithString: is autoreleased, so its retain count is effectively already going to be zero when the next autorelease pool is drained. Releasing it explicitly like you're doing will bring its retain count to 0 immediately, resulting in deallocation. Then, when the autorelease pool is drained, it'll try to release that string again, resulting in a crash.

It's always best to use the Build and Analyze command in Xcode. It can pick up and warn you about almost all memory leak issues, although it's not perfect. Still, it's a good practice.

@BoltClock, I think you are not entirely correct in saying that the object is autoreleased in sample 1.

In sample 2, a variable named url is assigned the object returned from the [NSUrl URLWithString:] method, thus incrementing its retain count by 1. To balance that, we need to release it. While in sample 1, the reference to the object is directly passed to the receiver and we have nothing to worry about its retain count, hence no release.

Note that we are not autoreleasing, since we have not retained anything in the first place. "There is no variable in the code that is being autoreleased!"

Please correct me if I am conceptually wrong somewhere. And just to complete this, there is no leak in either of the samples and both are correct ways of doing this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM