Slowly I study Swift and the question arose when to use dispatch_async(dispatch_get_main_queue(), {...}) correctly dispatch_async(dispatch_get_main_queue(), {...}) . The strange behavior of the UIAlerController led to the question. Sometimes when I call him, he writes that the pier is not on the main thread and will subsequently lead to weird crashes . Elijah, when I close the program, writes that the pier cannot close until something is dismissing . Subtracted that it is necessary to use dispatch_async , it seemed to help, but how is it right? In all cases in it to cause / close? And in general, what actions and when is it better to write in dispatch_async ?

    1 answer 1

    1. The entire UI needs to be updated only from the main thread.
    2. This code will update the UI, but will wait for the operation to complete. It is better not to do that.

       dispatch_sync(dispatch_get_main_queue(), ^{ // Update the UI on the main thread. }); 
    3. And this correct code will update the UI, but will not slow down the current thread.

       dispatch_async(dispatch_get_main_queue(), ^{ // Update UI }); 
    • And how do I know if I am updating from the main stream or is it not in the main stream and need to be assigned to dispatch_async? - Son'ka V
    • @ Son'kaV to find out if the current code is being executed in the main thread, you can use NSThread.currentThread (). IsMainThread - Denis