29

I have method which makes UI changes in some cases.

For example:

-(void) myMethod {

  if(someExpressionIsTrue) {
    // make some UI changes
    // ...
    // show actionSheet for example
  }
}

Sometimes myMethod is called from the mainThread sometimes from some other thread.

Thats is why I want these UI changes to be performed surely in the mainThread.

I changed needed part of myMethod this way:

if(someExpressionIsTrue) {
     dispatch_async(dispatch_get_main_queue(), ^{
        // make some UI changes
        // ...
        // show actionSheet for example
      });
}

So the questions:

  • Is it safe and good solution to call dispatch_async(dispatch_get_main_queue() in main thread? Does it influence on performance?
  • Can this problem be solved in the other better way? I know that I can check if it is a main thread using [NSThread isMainThread] method and call dispatch_async only in case of other thread, but it will make me create one more method or block with these UI updates.
B.S.
  • 21,660
  • 14
  • 87
  • 109
  • 1
    It is not necessary to create anothet block or function using the [NSThread isMainThread] as a condotion. You can recursively call back the original function on mainthread if it is called from some other thread. It is just 2 lines of code and one more if statement to perform. – Balazs Nemeth Jan 08 '14 at 20:36

2 Answers2

39

There isn't a problem with adding an asynchronous block on the main queue from within the main queue, all it does is run the method later on in the run loop.

What you definitely don't want to do is to call dispatch_sync adding a block to the main queue from within the main queue as you'll end up locking yourself.

Abizern
  • 146,289
  • 39
  • 203
  • 257
  • 1
    And especially don't use the (now deprecated for iOS) `dispatch_sync(dispatch_get_current_queue()`, which had the 'feature' of sometimes blocking, sometimes not, depending on whether you were called on the main thread or not! – sapi Sep 17 '13 at 11:42
6

Don't worry if you are calling dispatch_async in main thread or not. iOS will put the block in a queue and execute the block in main thread.

Zhengming Ying
  • 447
  • 4
  • 6