开发者

Common HTTP request delegate pattern in Objective-c (iOS)

I have a view controller "myViewController" that makes HTTP requests. I set the request's delegates to self (the instance of myViewController). Everything works fine until I pop myViewController off the navigation stack before a request returns. In this case the request tries to send a message to the dealloc'd myViewController (which causes my app to crash).

Currently I'm patching/solving this problem by setting the delegate of all requests to nil in myViewController's dealloc method. What's a bette开发者_运维百科r way to do this?

Perhaps a singleton could be responsible for handling all HTTP requests?


A while ago I had this same problem for UIWebView delegate events. The solution is to keep track of all outgoing HTTP requests within your myViewController. So, keep an instance variable called mutableRequests onto which you add every request that you send. It will probably also be a good idea to remove requests from this array once they are finished.

In the -viewWillUnload method, simply enumerate through mutableRequests and cancel every request. This will not only allow you to cancel all requests before your view is deallocated, but it will also help you respect the release/retain programming model by retaining all of the objects in an array while they are in use.


Depends on what you're view controller is doing. If the requests are only relevant in that VC, then do what Alex is suggesting. If your app revolves around the requests (central part of functionality), you'll probably want that singleton. You'd probably also want a common delegate that all your view controllers implement, so that whatever is the present view controller can handle your delegate call. Obviously, your request-handling singleton will serve as the actual delegate of your requests, and call your delegate methods as necessary.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜