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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With