Reputation: 3456
I can't seem to word this question well enough to get fruitful search results.
If I change the foremost view controller while waiting on a network connection to finish, should I build error handling around the network request? Or can I expect the callback block to message nil
and nothing happen? Or is there some preprocessor magic that politely stops the process?
Is the answer to above the same for all processes not on the main thread?
Upvotes: 1
Views: 112
Reputation: 53850
You should cancel the request if the delegate for an asynchronous request is a view controller and that view controller is becoming inactive.
If you do not cancel the request, you may be attempting to do things that are no longer relevant to the user. We had this issue once and the user was seeing pop-up alerts that were not relevant.
If you are using NSURLConnection
, simply call the cancel
method. You'll generally have to keep a strong pointer around for the NSURLConnection
object so that you can do this.
A good place to cancel the request is in prepareForSegue
just prior to switching to another view.
With a navigation controller (push segue) or a modal segue, the view controller is kept on the stack, so it will not be released. Your delegate method will still be called. Even in other circumstances, you may run into race conditions, so always cancel.
You should also consider cancelling the request in your view controller's viewWilLDisappear
method. If the user clicks the home button before the request receives a response, then returns to the application, the request will most likely error (time out). If you're not doing anything when the connection errors, you're good, but if you're displaying an error, the user won't expect to see an error as soon as they relaunch the app.
The answer's pretty much the same for all processes that relate to a particular view, assuming the MVC paradigm.
In some cases, the delegate to an asynchronous request may be an instance of a separate class (not the view controller), and instead of cancelling, you'll always process the response, even in the same thread (main run loop). I do this when I'm updating content "in the background".
Upvotes: 3