7

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.

Jim
  • 5,940
  • 9
  • 44
  • 91

2 Answers2

13

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.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • I swear I've answered this before, but I can't find the duplicate. /me shrugs – jscs Feb 21 '12 at 18:53
  • Thanks for the quick answer, Josh. This is the answer I have seen, which I will implement. Since both answers are tagged with the same time, I will give Fscheidl the green check, and give you an up vote. I hope you don't 'mind. – Jim Feb 21 '12 at 19:00
  • 2
    Glad I could help. I've got more rep than I know what to do with, so no, it doesn't matter, thanks. – jscs Feb 21 '12 at 19:02
  • "dispatch_sync(dispatch_get_main_queue(), block)" freezes the UI. Any suggestion? – x4h1d Jul 03 '13 at 08:44
  • @x4h1d Calling it from the main thread? That way you create a deadlock. – tillaert Jun 13 '14 at 12:06
12

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
        });    
});
fscheidl
  • 2,281
  • 3
  • 19
  • 33
  • 1
    It seems these two are not equivalent according to [this SO question](http://stackoverflow.com/questions/9335434/whats-the-difference-between-performselectoronmainthread-and-dispatch-async-on-m). Also [this](http://stackoverflow.com/questions/19544207/how-to-avoid-coreanimation-warning-deleted-thread-with-uncommitted-catransactio) for a more UI-specific answer. – insys Dec 30 '13 at 12:52