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 initWithReq开发者_高级运维uest:delegate:]
in one method and then release
s 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
:
+[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 autorelease
d 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 release
s 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.
精彩评论