performSelectorOnMainThread and detachNewThreadSelector

from MobileAppMastery/Threading/02

Basically detachNewThreadSelector detaches a thread and starts its work process. When you need to update the UI, you do it on the main thread. We use performSelectorOnMainThread to do it. We make our main thread perform a chunk of code.

1) get the big task going with:

2) the big task will be running with a ridiculous for loop. Let’s remember to put everything within an autoreleasepool because we want the garbage collection to do its work right away within this cycle.

3) so we’re running happily and this big task is being finished on a separate thread. But what if we want to update the UI? We do it with the performSelectorOnMainThread method:

Basically we run a chunk of code on the main thread. This chunk of code in our case is getting the progress bar to set a new percentage.
Now, the other thing we have to take care of is WHEN do we do this update? In our case, we just do this every time it hits a thousand.
We keep the counter variable ‘updateUIWhen’ to increment by 1000 everytime we update the UI. That way, it i will run 1000 times more before
it does the next update.

Obviously, this is just an example of updating the UI incrementally. You can use whatever method you’d like.

full source:

Leave a Reply