Please help! Have been staring at this for 12 hours; and have looked online and can't find solution.
In my application, I use 2 UIView controls in separate pages/controllers:
- UIImageView (retrieve data via
NSData dataWithContentsOfUrl)
- UIWebView
Just to isolate my code, and make it easier to explain, I created a new view based project called "MyTestApplication"
1 - I added a simple NSData dataWithContentsOfUrl in the delegate function.
NSData *imageData = [NSData dataWithContentsOfURL:
[NSURL URLWithString:@"http://www.google.com/intl/en_ALL/images/logo.gif"]];
(Nothing to release here since it's all using convenience functions)
alt text http://img.skitch.com/20081110-j5tn5n7ixph95ys4rpchibaw5p.preview.jpg
View Image
2 - Run it to verify no leaks (as expected)
alt text http://img.skitch.com/20081110-fy2qrkgy47hm4fe2f1aakd4muw.preview.jpg
View Image
3 - Open the ViewController.xib and simply add a UIWebView from the library (no need to wire it up)
alt text http://img.skitch.com/20081110-d63c3yh1a1kqiciy73q8uyd68j.preview.jpg
View Image
4 - Run it to verify there are leaks! (why???)
alt text http://img.skitch.com/20081110-qtxcfwntbcc3csabda3r6nfjg6.preview.jpg
View Image
What am I doing wrong? Please help!
Why would NSData cause memory leak if I'm using UIWebView? I just don't get it.
Thanks.
I was also having trouble with leaks from NSData's dataWithContentsOfURL:
in the iPhone simulator. I found that when I used the other convenience method (dataWithContentsOfURL:options:error:
) I would not get the memory leak.
My code looked something like this:
NSURL *url = [NSURL URLWithString:urlString];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfURL:url
options:0
error:&error];
Link to documentation
I think this is what's happening:
When ViewController.xib is loaded, an instance of UIWebView is allocated and initialized. Since you're not wiring it up anywhere, it's not getting released. I think you need to wire it up and release it in your backing View Controller's dealloc function. I remember having to manually release every object I created in a xib file.
Are you running Leaks on the Simulator? If so, caveat coder. The Simulator will leak memory where the iPhone hardware won't. No simulator is ever a perfect match for the exact behavior of your code on the device.
I would test on the device as well. I just did the same thing on a similar issue with UITableViewController which was leaking in the Sim but not on the phone.
[NSData dataWithContentsOfURL:url options:0 error:&error]
did not help me on iOS8.
But following works correctly:
NSURLRequest* request = [NSURLRequest requestWithURL:imageURL];
NSData* imageData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
[[NSURLCache sharedURLCache] removeCachedResponseForRequest:request];
Production code would need also response and error parameters.