简体   繁体   中英

Abandoning network requests in iOS apps

After I push myViewController onto the navigation stack I make a simple network request for some data that populates a few fields on myViewController. I don't want this request to block the main thread so I make it using performSelectorInBackground . When the request returns I use performSelectorOnMainThread to update the UI.

This approach works fine except for abandoning the request. Say the user pushes the view controller, the network request starts, then the user immediately pops the view controller and does something else in the app. In this case the network request comes back to a non-existent object. How can I handle this case?

I've considered a more robust networking layer where each request has a delegate the handles the response. Using this architecture I could nil out the delegate when the view controller is popped hence avoiding the problem of the request returning to nothing. I'm not sure if this is the best way to go.

I don't want this request to block the main thread so I make it using performSelectorInBackground.

So you're making a synchronous request -- one that'll block the thread that it's running on. Instead of doing that, make the request asynchronous using, for example, +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:] . You can then make the request from whatever thread you like, including the main thread -- no need for -performSelectorInBackground: . When the connection changes state, your delegate will be notified using the NSURLConnectionDelegate protocol. This way, you can send a -cancel message to the connection to stop it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM