Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Block version of performSelectorOnMainThread:withObject:waitUntilDone:

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.

like image 421
Jim Avatar asked Feb 21 '12 18:02

Jim


2 Answers

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.

like image 192
jscs Avatar answered Nov 05 '22 09:11

jscs


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
        });    
});
like image 41
fscheidl Avatar answered Nov 05 '22 07:11

fscheidl