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 better 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 calledmutableRequestsonto 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
-viewWillUnloadmethod, simply enumerate throughmutableRequestsand 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.