Is there a way that I can execute a block rather than a selector corresponding to this and similar methods?
I have observers that may receive events that aren't generated on the main thread. I want the action to be performed on the main thread if it is primarily UI oriented. Right now, I need to write two methods to do this, where one is the event observer, and the second is the code that needs to be executed on the main thread.
I would like to encapsulate this all into one method, if I could.
GCD should do the trick:
dispatch_sync(dispatch_get_main_queue(), ^{
// Do stuff here
});
Or dispatch_async
if you were planning on waitUntilDone:NO
. The main queue is guaranteed to be running on the main thread, so it is safe for UI operations.
The preferable technology for block-supporting multhreading actions is called Grand Central Dispatch. You can find some sample code on Wikipedia and in the Grand Central Dispatch (GCD) Reference
dispatch_async(backgroundQueue, ^{
//background tasks
dispatch_async(dispatch_get_main_queue(), ^{
//tasks on main thread
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With