Sorry if this has been asked before, but I’m wondering what the best memory management practice is for NSURLConnection. Apple’s sample code uses -[NSURLConnection initWithRequest:delegate:] in one method and then releases in connection:didFailWithError: or connectionDidFinishLoading:, but this spits out a bunch of analyzer warnings and seems sort of dangerous (what if neither of those methods is called?).
I’ve been autoreleasing (using +[NSURLConnection connectionWithRequest:delegate:]), which seems cleaner, but I’m wondering–in this case, is it ever possible for the NSURLConnection to be released before the connection has closed (for instance, when downloading a large file)?
This returns autoreleased
NSURLConnection:If you want to keep the reference you need to
retainit. Once you are done thenreleaseit.It does not help to
autoreleasealreadyautoreleased object.I assume the example code will somewhere
retaintheNSURLConnectionand thenreleaseit when the connection fails, as shown in your example.This returns allocated object that you have to take care of cleaning
Because the method is named
init, the other one above does not haveinitin the name orcopyso you don’t have to worry about the memory management.If your object internally creates
NSURLConnectionat some point and thenreleases it when connection is done or failed you should reset the reference to nsurlconnection tonil.In your
deallocyou should cleanup theNSURLConnectionas well, if it isnilnothing will happen but if it is still allocated it will clean it up.See apple doc about memory management – it’s quite simple.