How to perform network task in background thread while updating UITableView?
just trying to figure out what would be the best way to design such functionality? Basically i send an asynchronous NSURLConnection which hits a server that sends back a bunch of data. Once i get the data i have to perform some work on it which is pretty expensive and which i would rather do in a bg thread to prevent the UI from locking. Lastly i also need to have a uitable update dynamically as the response from the server is received and processed.
My question is how would i go about doing that work in a background thread as the data arrives so that the table doesnt wait until all the data has loaded before being updated??
This is my pseudo code I have so far. In my ViewController i would have two BOOL flags newDataReceived and dataFinishedDownloading. I would also have two variables, a string that contains the current data and a nsarray that kept the results of processing the data. Then,
- in didReceiveResponse: i would spawn a new thread by calling performSelectorInBackground: with the processing method as the selector.
- in that method i would have a loop that would first check newDataReceived to see if new data has arrived and if so do some work on it.
- once finished processing i would then set the nsarray with the results and then call another method that updates the table datasource and reloads the table using performSelectorOnMainThread:
- Lastly i would check the dataFinishedLoading flag to see if there is any more data to process
- if there is still data and would start all over again, otherwise cleanup the thread and exit
Also the newDataReceived flag would be set in didReceiveData: as开发者_高级运维 well as the actual data received. Finally in didFinishLoading i would set the dataFinishedLoading flag to signal that all the data has been loaded.
I plan on using NSLock's in #2-4 when checking the status flags as well as getting and setting the received data string and results nsarray.
Im sure there are a number of ways to do the same thing but does this seem like a good way to go about it?
thx
You could take a look at NSOperation and NSOperationQueue. NSOperation is a perfect alternative for doing heavy calculations and operations in the background. If you need continuously updates to the tableview you could implement some protocol in your Operation to handle callbacks to the tableview.
What you are looking to do can be achieved with the performSelectorOn... methods. Have a look at this: http://arstechnica.com/civis/viewtopic.php?f=20&t=49035
Just keep in mind that UI updates should be done in the main thread (so use performSelectorOnMainThread for UI updates).
精彩评论