开发者

Memory management for NSURLConnection

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 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:

+[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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜