NSURLConnection Leak - iphone

Today i faced a little problem, i wanted to know the reason of leak. Here is the code
[[NSURLConnection alloc] initWithRequest:request delegate:self];
This works fine no problem.
Now i was just wondering what happens to this allocated memory/object since no one is releasing it. So according to instinct i put autorelease while allocating like this:
[[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
This threw me an error and crash "[NSURLConnectionInternalConnection _withConnectionDisconnectFromConnection]: message sent to deallocated instance"
Just wanted to know the concept and reason behind.
EDIT: I am not using ARC.
Thanks.

I think you can not use autorelease here for better memory management please release connection object in connection delegate method
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
[connection release];
}
So when your connection get finished It will release the connection object or you can release it ni viewDidUnload also

[NSURLConnectionInternalConnection _withConnectionDisconnectFromConnection]
this was called after the Autorelease Pool released your NSURLConnection connection object.
Best way should be, have a reference for the variable and release it, once you are done fetching the data. (May be in the viewDidUnload: ?)

You can use this method for better memory management
NSURLConnection *connection=[NSURLConnection connectionWithRequest:urlRequest delegate:self];
Above connectionWithRequest method is class method and manage memory itself you don't need to release it.
As far as I know after allocating the connection object objc runtime adds the object to autoreleasepool then other delegate method sent to deallocated instances.

Related

how to use auto-release in iphone

I want to use the auto-release in my apps. I want to implement this methods
- (void)selectorConnect: (NSArray *)args
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
//some code
[pool release];
}
Getting crash at [pool release] line. Any solution for that .
When you empty an autorelease pool, it calls autorelease on all objects inside it.
If you're getting a crash with the [pool release] line then you've added an object to the autorelease pool and have released it yourself.
Run the static analyser and see what warnings it gives you.
And if you still don't know, enable NSZombies and see what object is being released twice.
Finally, if that still doesn't help, add your code to the question and we can all take a look :)

Asynchronous NSURLConnection on separate thread fails to call delegate methods

I am running a NSURLConnection on a separate thread (I am aware that it is asynchronous and works when running on the main thread), but it is not making delegate calls even when I pass the parent thread as the delegate. Does anyone know how to do this?
Code:
-(void)startConnectionWithUrlPath:(NSString*)URLpath {
//initiates the download connection - setup
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
//initiates the download connection on a seperate thread
[NSThread detachNewThreadSelector:#selector(startDownloading:) toTarget:self withObject:self];
}
-(void)startDownloading:(id)parentThread {
NSAutoReleasePool *pool = [[NSAutoReleasePool alloc] init];
[NSURLConnection connectionWithRequest:myURLRequest delegate:parentThread];
//The delegate methods are setup in the rest of the class but they are never getting called...
[pool drain];
}
EDIT*
The reason I need to run NSURLConnection on a separate thread is because I am downloading something in my iPhone app and the download cancels when the user locks the screen (it continues fine if the user simply presses the home button and the app goes into the background). I understand this is due to my running the connection asynchronously on the main thread and not a separate one.
I have also tried this code (NOT in a separate thread) when initiating the NSURLConnection:
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:myURLRequest delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[connection start];
[connection release];
But it I have the same problem with this regarding the download being cancelled on screen lock.
*UPDATE
To add to Thomas' answer below (Please note that James Webster's answer is also correct regarding the exiting of a thread) the Apple docs explain:
"Suspended state - The app is in the background but is not executing code. The system moves apps to this state automatically and does not notify them before doing so. While suspended, an app remains in memory but does not execute any code."
Since when the screen is locked by the user the app is put into the background state and than right away into the suspended state, all execution is stopped killing any downloads and no warning that this is about to happen is given... there may be a notification which tells me that the user has locked the screen but I haven't found one yet.
I therefore pause (save certain information and cancel the NSURLConnection) all downloads when the app goes into the background and resume it with the HTTP Range header when it gets active again.
This is a workaround which is ok but not ideal since the download is not occurring in the background which affects the user experience negatively... bummer.
Since your NSURLConnection is asynchronous, the end of your -startDownloading method is reached immediately, and the thread exits.
You should indeed schedule your connection on the main runloop (or use GCD).
The device lock is another issue. When the device is locked, your application is suspended to save battery life. You can probably ask for an extra amount of time when suspending in order to finish your download.
I think your problem might be that the NSURLConnection has been deallocated as soon as you exit the startDownloading: message (or more accurately when your autorelease pool is drained)
However I think your methodology might be a bit uncouth anyway. NSURLConnection the way you are using it is asynchronous and will appear to be threaded anyway.
Try this and see if it works as you expect it to (i.e. your app doesn't pause while your connection is busy)
-(void)startConnectionWithUrlPath:(NSString*)URLpath {
//initiates the download connection - setup
NSURL *myURL = [[NSURL alloc] initWithString:URLpath];
myURLRequest = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[myURL release];
[NSURLConnection connectionWithRequest:myURLRequest delegate:self];
}

iOS: ASIHTTPRequst synchronous on background selector bad idea?

I was using NSURLConnection in a synchronous way before running on a background selector, so when I moved over to ASIHTTPRequest I did the same with this framework.
So, is it a bad idea to do something like the following?
// From another method
[self performSelectorInBackground:#selector(callDatasource) withObject:nil];
- (NSData *)callDatasource {
NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:someURLthatIamusing];
[request setTimeOutSeconds:50.0];
[request startSynchronous];
NSError *error = [request error];
NSData *returnedData;
if (!error) {
returnedData = [request responseData];
} else {
// do something with error
}
[self performSelectorOnMainThread:#selector(done) withObject:nil waitUntilDone:NO];
[apool release];
return returnedData;
}//end
What would be the advantage to use the ASIHTTPRequest and asynchronous methods along with the delegate methods?
From experience, sometimes odd things can happen when using ASIHTTPRequest synchronous requests off a secondary thread: the download activity icon in the status bar not disappearing upon download completion is one issue I've noticed from time to time. I've had no major problems in the past, but I use the asynchronous methods now rather than your approach. The ASI asynchronous methods are by the nature of being a widely used library more highly tested than my own implementation could ever be.
There are a number of advantages with using the asynchronous methods - you mention the delegate methods, but the latest release of ASI actually also supports blocks, which is a great leap forward (dealing with multiple synchronous calls used to be a bit of a pain due to the shared delegate methods (or unique delegates for each asynchronous call). But with blocks you can now get rid of the delegates entirely. I've found them to be really useful. Plus if you use multiple contributors it can make readability a lot easier.
Also, by doing it Async, you can more easily track progress through the setProgressDelegate command.

Iphone: Need release using ASIFormDataRequest

i have one simple question, if i'm using ASIFormDataRequest when i need to release the request object?
NSURL *url = [NSURL URLWithString:#"url"];
ASIFormDataRequest *requestForm = [ASIFormDataRequest requestWithURL:url];
[requestForm addPostValue:[[NSUserDefaults standardUserDefaults] stringForKey:#"user"] forKey:#"user"];
[requestForm setRequestMethod:#"POST"];
[requestForm setDelegate:self];
[requestForm startAsynchronous];
Thanks
You need to remember that you are always responsible for releasing an object if the method from which you receive it contains new, copy, or init.
In this case, you don't need to release it. The ASIHTTPRequest class autoreleases it for you.
A quick search in the implementation file shows that it'll be autoreleased.
+ (id)requestWithURL:(NSURL *)newURL
{
return [[[self alloc] initWithURL:newURL] autorelease];
}
Your request is autoreleased in your code, so you don't need to release it (as others have said).
However, you are starting an asynchronous request - it'll complete/fail sometime in the future, and if it is associated with other objects which will get freed when the view exits you're potentially leaving yourself open to a crash. So I'd suggest you would want to make requestForm a property of your class (so when you assign the request to self.requestForm it will get retained for you), and explicitly release & nil it when the request completes.
If it's a very simple app with just one view you may get away without that though.

Can canceling a NSURLConnection lead to problems?

Before my view loads I call:
[theConnection cancel]; //assume theConnection is an NSURLConnection
I then proceed and make my proper NSURLConnection.
Will calling cancel before a connection is even made cause any problems?
No, the NSURLConnection documentation makes it clear that cancel is possible and that the delegate will receive no further messages once it is called. Also that the delegate is released on cancel.