开发者

Memory management, and async operations: when does an object become nil?

I have a view that will be displaying downloaded images and text. I'd like to handle all the downloading asynchronously using ASIHTTPRequest, but I'm not sure how to go about notifying the view when downloads are finished...

If I pass my view controller as the delegate of the ASIHTTPRequest, and then my view is destroyed (user navigates away) will it fail gracefully when it tries to message my view controller bec开发者_如何学Cause the delegate is now nil?

i.e. if i do this:

UIViewController *myvc = [[UIViewController alloc] init];
request.delegate = myvc;
[myvc release];

Do myvc, and request.delegate now == a pointer to nil?

This is the problem with being self-taught... I'm kinda fuzzy on some basic concepts.

Other ideas of how to handle this are welcome.


update: Looking at the source code for ASIHTTPRequest, it does not retain its delegate, so your code will either have to ensure that the delegate has not been released, or set the request's delegate property to nil before releasing your controller.

If you are going to have several asynchronous HTTP requests running, it may be a good idea to create an HTTPRequestManager class to act as delegate for all of your HTTP requests. This HTTPRequestManager class would remain in memory for the entire lifetime of your application, and it could take care of failing gracefully if/when your view controllers are released.

I would like to add a clarification about Cocoa's reference-counted memory management. It is important to remember that a released object is not automatically set to nil. Sending a message to nil is perfectly legal (and simply does nothing), but sending a message to a deleted object is undefined behaviour. Keeping a pointer to a deleted object is asking for trouble, and such living/dead pointers are referred to as zombies.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜