开发者

Does this objective-c code cause memory leak?

开发者 https://www.devze.com 2023-02-08 13:19 出处:网络
Compare the following 2 snippets: sample 1: [[UIApplication shareApplication] openURL: [NSURL URLWithString:@\"http://stackoverflow.com\"]]

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: u开发者_如何转开发rl];
[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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号