UIKit, AppKit等类的进程处理

新博客地址:https://gyrojeff.top,欢迎访问! 本文为博客自动同步文章,为了更好的阅读体验,建议您移步至我的博客👇

本文标题:UIKit, AppKit等类的进程处理

文章作者:gyro永不抽风

发布时间:2020年02月28日 - 21:02

最后更新:2020年09月15日 - 07:09

原始链接:http://hexo.gyrojeff.moe/2020/02/28/UIKit-AppKit%E7%AD%89%E7%B1%BB%E7%9A%84%E8%BF%9B%E7%A8%8B%E5%A4%84%E7%90%86/

许可协议: 署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0) 转载请保留原文链接及作者!

Overview

The Main Thread Checker is a standalone tool for Swift and C languages that detects invalid usage of AppKit, UIKit, and other APIs on a background thread. Updating UI on a thread other than the main thread is a common mistake that can result in missed UI updates, visual defects, data corruptions, and crashes.

How the Main Thread Checker Works

At app launch, the Main Thread Checker dynamically replaces the implementations of methods that should only be called on the main thread with a version that prepends the check. Methods known to be safe for use on background threads are excluded from this check.

Note

Unlike other code diagnostic tools, the Main Thread Checker doesn’t require recompilation, and can be used with existing binaries. You can run it on a macOS app without the Xcode debugger, such as on a continuous integration system, by injecting the dynamic library file located at /Applications/Xcode.app/Contents/Developer/usr/lib/libMainThreadChecker.dylib.

Performance Impact

The performance impact of the Main Thread Checker is minimal, with a 1–2% CPU overhead and additional process launch time of <0.1 seconds.

Because of its minimal performance overhead, the Main Thread Checker is automatically enabled when you run your app with the Xcode debugger.

Updating UI from a Completion Handler

Long-running tasks such as networking are often executed in the background, and provide a completion handler to signal completion. Attempting to read or update the UI from a completion handler may cause problems.

1
2
3
4
5
6
7
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
self.label.text = "\(data.count) bytes downloaded"
// Error: label updated on background thread
}
}
task.resume()

Solution

Dispatch the call to update the label text to the main thread.

1
2
3
4
5
6
7
8
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let data = data {
DispatchQueue.main.async { // Correct
self.label.text = "\(data.count) bytes downloaded"
}
}
}
task.resume()
posted @ 2020-09-15 09:12  gyro永不抽风  阅读(141)  评论(0编辑  收藏  举报