iOS
multithreading
dispatch_async
performSelectorOnMainThread
UI更新

Perform UI Changes on main thread using dispatch_async or performSelectorOnMainThread?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In iOS development, handling UI changes on the main thread is critical. This ensures the application remains responsive and behaves as expected. When updating the app's user interface (UI), developers can execute code directly on the main thread using either dispatch_async or performSelectorOnMainThread. However, it’s essential to understand how these methods work and when to use them to achieve efficient and safe UI updates.

Performing UI Changes on the Main Thread

The Importance of the Main Thread

iOS applications have a main thread, also known as the UI thread, responsible for drawing UI components and handling user interactions. Since the UI cannot be updated simultaneously by multiple threads safely, Apple mandates updates to UI components to happen on this main thread. Updating UI components from background threads can lead to race conditions, unexpected behaviors, and even crashes.

Using dispatch_async

dispatch_async is part of the Grand Central Dispatch (GCD) framework that provides a powerful way to manage concurrent code execution. Developers can use dispatch_async to schedule UI updates on the main thread as follows:

objective-c
1dispatch_async(dispatch_get_main_queue(), ^{
2    // Perform UI updates here
3    self.label.text = @"Updated text";
4});

Technical Explanation:

  • dispatch_get_main_queue() returns the main dispatch queue, which is associated with the main thread.
  • dispatch_async will place the block of code on the main queue for execution.
  • This is a non-blocking call, which means it will return immediately without waiting for the completion of the code block.

When To Use:

  • Use dispatch_async when you want to perform UI updates asynchronously and ensure they happen on the main thread.
  • It is especially helpful when coming from background threads after performing time-consuming operations.

Using performSelectorOnMainThread

performSelectorOnMainThread is a method that sends a message to the main thread. It can be used to trigger a selector on the main thread directly:

objective-c
[self performSelectorOnMainThread:@selector(updateUI)
                       withObject:nil
                    waitUntilDone:NO];

Here, updateUI is a method that contains the UI update logic.

Technical Explanation:

  • performSelectorOnMainThread:withObject:waitUntilDone: sends a message to the main thread to invoke the specified method.
  • waitUntilDone determines whether the call should block and wait, which can be useful if the next code depends on the UI updates being finished.

When To Use:

  • Opt for performSelectorOnMainThread when you need a simple way to ensure that specific messages are executed on the main thread.
  • It provides a straightforward mechanism for switching to the main thread but lacks some of the flexibility of GCD.

Comparison and Use Cases

Let's summarize the key features and considerations of using dispatch_async versus performSelectorOnMainThread:

Feature/Considerationdispatch_asyncperformSelectorOnMainThread
Thread ManagementUses GCD's dispatch queue to manage threadingDirectly sends message to the main thread
FlexibilityOffers greater control and flexibilityLimited to method invocation on objects
PerformanceEfficiently handles asynchronous tasksMay involve more overhead due to selector messaging
Blocking BehaviorAlways non-blockingCan block if waitUntilDone is set to YES
SimplicityRequires a block of codeSimple to call with selector methods
Complexity of tasksSuitable for larger or more complex tasksBest for simpler tasks or method-specific calls

Conclusion

Handling UI updates carefully in iOS applications is critical for a responsive and crash-free experience. Both dispatch_async and performSelectorOnMainThread serve their purposes well under different situations. Choosing between these methods often depends on the complexity and nature of the task, as well as the need for asynchronous versus synchronous behavior.

Utilizing the appropriate method not only ensures that UI updates are performed safely but also aligns with best practices in modern iOS development. By understanding the strengths and limitations of each approach, developers can build robust and user-friendly applications.


Course illustration
Course illustration

All Rights Reserved.