Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 795
Haoest Avatar asked Sep 19 '26 14:09

Haoest


2 Answers

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).

like image 111
BoltClock Avatar answered Sep 21 '26 05:09

BoltClock


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.

like image 23
CIFilter Avatar answered Sep 21 '26 05:09

CIFilter