NSURLConnection leak? - objective-c

i have set up a nsurl which grabs the data from http.
when i run instrument, it says i have a leak NSFNetwork object.
and how do i release theConnection in (void)ButtonClicked? or it will be release later on?
- (void)ButtonClicked {
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:KmlUrl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:20.0f];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// receivedData is declared as a method instance elsewhere
NSMutableData *receivedData = [[NSMutableData data] retain];
[self setKMLdata:receivedData];
} else {
// inform the user that the download could not be made
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// append the new data to the receivedData
// receivedData is declared as a method instance elsewhere
[KMLdata appendData:data];
NSLog(#"didReceiveData");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// release the connection, and the data object
[connection release];
[KMLdata release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[KMLdata release];
}

I finally found the answer for this.
The error in the above code (which by the way is the near-exact sample from the SDK docs) is not in the memory management code. Autorelease is one option, manual release is another. Regardless of how you handle your NSURLConnection object, you get leaks using NSURLConnection.
First up, here is the solution. Just copy these 3 lines of code directly into connectionDidFinishLoading, didFailWithError and anywhere else you release the NSURLConnection object.
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:0 diskCapacity:0 diskPath:nil];
[NSURLCache setSharedURLCache:sharedCache];
[sharedCache release];
Credit to mpramodjain on http://forums.macrumors.com/showthread.php?t=573253 for the code.
The problem seems to be this – the SDK caches the requests and replies on the iPhone. Even it seems if your NSMutableURLRequest cachePolicy is set to not load the reply from the cache.
The silly thing is that it seems to cache a lot of data by default. I'm transmitting a lot of data (split into multiple connections) and started to get memory warnings, and finally my App died.
The docs we need are in NSURLCache (not NSURLConnection), they state:
NSURLCache implements the caching of
responses to URL load requests by
mapping NSURLRequest objects to
NSCachedURLResponse objects. It is a
composite of an in-memory and an
on-disk cache.
Methods are provided to manipulate the
sizes of each of these caches as well
as to control the path on disk to use
for persistent storage of cache data.
Those three lines have the effect of nuking the cache totally. After adding them to my App (GPS Log), my #living object count remains steady.

Hello have you test this delegate method ?
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
return nil;
}
You can manage the cache more precisely.
"reset" NSURLCache *sharedCache can cause problems on other part of your code ?

This is a common question and is solved by the magic of [object autorelease]. In your code this would be as follows:
NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
In this way, the object is automatically added to the "autorelease pool" and dealloc'd at the start of the next run loop after it is no longer referenced.
Hope that helps
Edit: Also, I don't see why you're needing to call -retain on your receivedData variable.

I am using the static method/autoreleased approach and it appears to work fine:
[NSURLConnection connectionWithRequest:theRequest delegate:self];
This way you don't even have to worry about releasing in the delegate callbacks. It turns out that the retain count of the connection is actually 2 (not 1) after it is alloc'd in the examples above, which changes the way I thought about this memory "leak."
#rpetrich I actually don't think you need to worry about the delegate being released before the connection is released. The connection retains it's delegate and the connection itself is actually retained by some sort of open connections queue. I wrote a blog post on my experiments with NSURLConnection on my blog:
"Potential leak of object" with NSURLConnection

Related

ios - Passing on data to another method - same viewController

Please see this code as an example:
-(void)generateConnection
{
NSString *urlString = #"";
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"%#", connection);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSString *partialData = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
[_jsonContentForText appendString:partialData];
NSLog(#"%#", partialData);
}
Really for lack knowing what it is called, but after searching - a lot - I am unable to out what this process is called.
I need to know how -(void)connection: gets the information it needs from the previous method. I don't know if this is called passing on methods to another method, but I need to create another one, so I need to know where I can learn this.
Please spare me the lines like: You need to read up on objective-c and the general stuff, because those answers do not cover the specific need I have.
I do not mind reading up on it, as long as I know what I am reading explains this. However if in any kind hearts it is easy to explain, I will not reject that offer:-)
You need to read up on Delegates and Protocols. When you create the NSURLConnection and set self as the delegate, your new NSURLConnection object is told to query self (the object that created it) to do things like find out if authentication is supported, or what to do when it receives some data. For the NSURLConnectionDelegate specifically, if your delegate implements the methods defined in NSURLConnectionDelegate Protocol, they'll be called.
Some good sources to read up on Delegates and Protocols are:
Working with Protocols(Apple)
Delegates and Data Sources(Apple)
The Basics of Protocols and Delegates(Mobile Developer Tips)

Asynchronous NSURLConnection call

I am making a Asynchronous NSURLConnection call and downloading the data, how can I know when this thread is completed?
I am making this call from viewDidLoad, and obviously NSURLConnection is intuitively running in separate thread. So how would I know if the thread is completed and second wait until the thread gets completed to get the data pulled to the viewcontroller.
You will need to assign a delegate to the NSURLConnection that handles the processing and what-not of the data. Check out the documentation, it's pretty straightforward!
code speaks for itself
-(void) startRequest {
NSURLRequest* req = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://stackoverflow.com"]];
[[NSURLConnection alloc] initWithRequest:req delegate:self];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
}

How to handle different requests using connectionDidFinishLoading in the same delegate?

Whenever I do a curl call using the below code:
NSURL *url = [NSURL URLWithString:requestURL];
NSURLRequest *request = [NSURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
timeoutInterval:30];
if (connectionInProgress) {
[connectionInProgress cancel];
}
connectionInProgress = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
connectionDidFinishLoading is my final destination where I can manipulate the response data and call my next methods to continue with the app . If I hard-code some specific tasks like
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSXMLParser *parser = [[NSXMLParser alloc] initWithData:xmlData];
[parser setDelegate:self];
[parser parse];
[someLabel setText:parsedTextFromXMLData];
}
If I need to do another curl call to a different address, wouldn't someLabel setText always get re-set again? Is there a way to make this delegate function behave differently on each curl call? (btw, is connectionDidFinishLoading usually the right place to put the next step of codes?) If so then wouldn't it always get called again by the next curl call?
Have a look at this S.O. post for a recipe concerning NSURLConnection and multiple requests.The suggestion is doing something like this:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == firstConnection) {
// do something
}
else if (connection == secondConnection) {
// do something else
}
}
EDIT: the idea here is that connectionDidFinishLoading is a method of your own delegate (so you write it). In the delegate, you store the address of each connection you create; then, when the connection comes back with the data, you tell which connection it is by comparing its address to the one you stored in the delegate. -END EDIT
Another option you have is using the ASIHTTPRequest framework, which offers a request-based (as opposed to connection-based) delegation mechanism, so each request has got a delegate object to handle the result; or, in other words, the delegate receives a reference to the request, so you can easily tell which request result you are handling.
ASIHTTPRequest offers a bunch of advantages over NSURLConnection. You can read about them in this S.O. post.
There're 2 options to do this:
you can implement a separate class, that will be responsible for handling NSURLConnection delegate stuff and create a separate instance for each request
you can use NSObject key-value methods on NSURLConnection instance for setting up some tag, that will be checked in connectionDidFinishLoading: method
For me, option 1 will be a better approach

Help with making NSURLConnection in a custom class

Hey all, I'm trying to use Yahoo's PlaceFinder to do reverse geocoding for an app I'm making. Problem is I need to use the NSURLConnection to call to my database. So I decided to make a custom class that is initialized with the user's latitude and longitude, and only store a string variable containing the state the user is in.
Update the following code now works fine....
Here is the .h
#import <Foundation/Foundation.h>
#import "CJSONDeserializer.h"
#interface StateFinder : NSObject
{
NSString *userState;
NSURLConnection *connection;
}
-(id)initwithLatitude:(NSString *)latitude andLongitude:(NSString *)longitude;
#property (nonatomic, retain) NSString *userState;
#property (nonatomic, retain) NSURLConnection *connection;
#end
and the .m
#import "StateFinder.h"
#implementation StateFinder
#synthesize userState;
#synthesize connection;
-(id)initwithLatitude:(NSString *)latitude andLongitude:(NSString *)longitude
{
if(self = [super init])
{
NSString *lat = latitude;
NSString *lon = longitude;
NSString *stateURLFinder = [NSString stringWithFormat:#"http://where.yahooapis.com/geocode?q=%#,+%#&gflags=R&flags=J&appid=zqoGxo7k", lat, lon];
//NSLog(stateURLFinder);
NSURL *stateURL = [NSURL URLWithString:stateURLFinder];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: stateURL];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[request release];
}
return self;
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"didFinishLoading");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError");
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Store incoming data into a string
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(jsonString);
// Yes, this is incomplete, but I was waiting for the method to fire before going
// any further. This will at least show me the JSON data being returned from yahoo
// in string format so I can output it to the console via NSLog
}
- (void)dealloc
{
[userState release];
[connection release];
[super dealloc];
}
#end
This is the current code I'm using and it works fine. All I did was include the connectionDidFinishLoading and didFailWithError methods to the original code. With regards to the connection being released before it was made, I used the code above as is without the previously mentioned methods and neither didReceiveData/didReceiveResponse would hit. It wasn't until those 2 methods were included that the methods began getting called. Not sure how, not sure why, but that was the only change among all of those suggested that worked. Big thanks to #Jiva DeVoe , #XJones , #jlehr and #Aby for all the tips/hints/suggestions!
Actually, I advise that you definitely do not use sendSynchronousRequest. You should always try to use asynchronous networking unless the app you're developing is a command line app without a run loop.
I suspect your problem may be that you're releasing the connection immediately, so it's never getting a chance to run. You should add a member variable and keep it around until you've received a response or whatever.
Bonus tip:
Guessing you're probably doing this for either iOS or the Mac, and writing GUI apps. These apps have run loops. When you use synchronous networking like the prior answer suggests, you prevent that runloop from executing. This means that if the request takes longer than a few seconds, your iOS app will be killed by the OS, and your Mac app will appear non-responsive. Neither of these are good results.
You're sending a release message to the connection before it's had a chance to run; don't do that. With regards to JSON, the string you said was returned from the server is JSON. Were you expecting something else?
Get rid of the line:
[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
Once you've initialized the connection with the request it runs automatically. You have other problems as well. Your implementation of the NSURLConnectionDelegate protocol is wrong. You need to incrementally add data received in connection:didReceiveResponse to an NSMutableData object. You can convert it to JSON in `connectionDidFinishLoading:'.
As for the memory leak, release the connection in connectionDidFinishLoading: or connection:didFailWithError: You are guaranteed to receive one but not both of them.
Everything you need to know is here
[EDIT: added NSURLConnection code sample]
// Attach this to the touchUpInside event of a UIButton
// Note that all objects will be autoreleased
// Note that you can comment out any or all of the NSURLConnection delegate methods
// and the request will execute
- (IBAction)initiateRequest
{
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL urlWithString:#"http://www.google.com"]];
NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didRecieveData:(NSData *)date
{
NSLog(#"connection:didReceiveData");
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"connection:didReceiveResponse:");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"connectionDidFinishLoading:");
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"connection:didFailWithError:");
}
Thanks to XJones for the suggestion. I wasn't including the two methods didFinishLoading or didFailWithError once inserted into my code, both didReceiveResponse and didReceiveData both began to hit. Thank you all for the tips, advice and suggestions and hopefully this helps someone else out down the road.

Why release the NSURLConnection instance in this statement?

I read this in a book.
-(IBAction) updateTweets
{
tweetsView.text = #"";
[tweetsData release];
tweetsData = [[NSMutableData alloc] init];
NSURL *url = [NSURL URLWithString:#"http://twitter.com/statuses/public_timeline.xml" ];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL: url];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection release];
[request release];
[activityIndicator startAnimating];
}
In this statement,is that correct to release the "connection" instance at that time? After releasing it which means this NSURLConnection instance will be destroyed since it's reference count is 0 ,how are we going to make this connection operation work after release this instance? THANKS.
I thought we should release it in one of the following callback methods,right?
connectionDidFinishLoading:
connection:didFailWithError:
It's actually fine to release it there, once the connection is sent out via initWithRequest, the only thing that matters is that the delegate exists or I believe the response will just be silently lost.
From what I can tell, the only reason to not release it there is if you want to call [connection cancel] at some point in one of the delegate functions, in which case it would be best to do what you suggest and release it in BOTH connectionDidFinishLoading and didFailWithError since only one of them will be called (right?).
Edit: For a more thorough answer, NSURLConnection initWithRequest is an asynchronous request. So it actually spawns it's own thread (but calls the delegate functions on the thread that called initWithRequest). So basically, on the thread that calls initWithRequest you are actually done with the connection object and you can release it. All the while it's doing stuff on some other thread that you don't need to be concerned with.
Also I should note that if you do release it there, make sure you DON'T release it in the finish/fail methods, because it won't be a valid object.