views:

137

answers:

1

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

+1  A: 

This returns autoreleased NSURLConnection:

+[NSURLConnection connectionWithRequest:delegate:]

If you want to keep the reference you need to retain it. Once you are done then release it. It does not help to autorelease already autoreleased object.

I assume the example code will somewhere retain the NSURLConnection and then release it when the connection fails, as shown in your example.

This returns allocated object that you have to take care of cleaning

-[NSURLConnection initWithRequest:delegate:]

Because the method is named init, the other one above does not have init in the name or copy so you don't have to worry about the memory management.

If your object internally creates NSURLConnection at some point and then releases it when connection is done or failed you should reset the reference to nsurlconnection to nil.

In your dealloc you should cleanup the NSURLConnection as well, if it is nil nothing will happen but if it is still allocated it will clean it up.

See apple doc about memory management - it's quite simple.

stefanB
Thanks, I was asking more specifically--is it safe to just autorelease it (i.e., would it be possible for the `NSURLConnection` to be released by the autorelease pool before it's actually finished)?
eman