Main Thread Checker

Tram Ho

Introduce

The Main Thread Checker is an independent tool that Apple integrated into Xcode 9 for Swift and C languages ​​to detect misuse for AppKit, UIKit and other APIs on the background thread . Updating the UI on a thread is different from the main thread and a basic error that we may encounter is likely to result in a buggy UI update, data corruption, or app crash.

How does the Main Thread Checker work?

When launching the app, the Main Thread Checker will automatically replace implementations of methods that should only be called on the main thread with a test version first. Methods that are known to be safe to use on background threads will be removed during the Main Thread Checker test .

Note:

Unlike other code diagnostic tools, the Main Stream Checker does not require recompilation and can be used with existing binary files. You can run it on a macOS application without the Xcode debugger, such as on a continuous integration system, by injecting the dynamic library file available at /Applications/Xcode.app/Contents/Developer/usr/ lib / libMainThreadChecker.dylib.

Performance

The performance impact of the Main Thread Checker is minimal, with a total CPU cost of 1% 2% and an additional process start-up time of <0.1 seconds. Because the operating cost is very small, the Main Thread Checker will automatically be enabled when you run your application with the Xcode debugger.

Updated UI from a Completion Handler

Below is an example of updating the UI from a Completion Handler , calling data from our API can take a long time, they are done in the background thread , when the API call is done We will update the UI.

The above code will cause an error, the required UI update must be done on the main thread . We will have to fix it as follows:

As I mentioned above, checking whether you are using the Main Thread or not will have the Main Thread Checker , and the result of running the Main Thread Checker is that the app will crash and it will show you where you used it wrong. .

However, in some situations, you accidentally turn off the Main Thread Checker feature without knowing it, at which point your UI update will always fail as the above case without any warning. It may take a long time to figure out why the UI isn’t up to date, which is annoying. You must always check that the Main Thread Checker is enabled by checking here:

Conclude

The Main Thread Checker is integrated into Apple and has helped developers to save a lot of time in the case of using the wrong Main Thread. Above I have introduced to you what it is and how it works, hope the article will be helpful to everyone. Thank you!

Source:

https://developer.apple.com/documentation/code_diagnostics/main_thread_checker

Share the news now

Source : Viblo