-[UIView setBackgroundColor:] must be used from main thread only

3010 ワード

ArticleMain Thread Checker
Detect invalid use of AppKit, UIKit, and other APIs from a background thread.
バックグラウンドスレッドからのAppKit、UIKEt、その他のapiの無効な使用を検出します.
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.
メインスレッドインスペクタは、SwiftおよびC言語の独立したツールであり、バックグラウンドスレッド上のAppKit、UIKEt、およびその他のapiの無効な使用を検出するために使用されます.メインスレッド以外のスレッドでUIを更新するのは、UIの更新が失われ、視覚的な欠陥、データの破損、クラッシュを引き起こす一般的なエラーです.
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.アプリケーション起動時、プライマリ・スレッド・インスペクタは、プライマリ・スレッドでのみ呼び出されるメソッドの実装を動的に1つのバージョンで置き換え、事前にチェックを実行します.バックグラウンドスレッドを安全に使用する方法は、このチェックには含まれていません.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は他のコード診断ツールとは異なり、プライマリスレッドインスペクタは再コンパイルする必要がなく、既存のバイナリファイルとともに使用できます.動的ライブラリファイルを注入することで、Xcodeデバッガを必要とせずにmacOSアプリケーション上で実行できます.たとえば、持続的な統合システムで/APplications/Xcode.app/Clontents/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.メインスレッドチェックプログラムの性能影響は最小であり、CPUオーバーヘッドは1-2%であり、プロセス起動時間は<0.1秒である.
Because of its minimal performance overhead,the Main Thread Checker is automatically enabled when you run your app with the Xcode debugger.パフォーマンスオーバーヘッドの最小化により、Xcodeデバッガを使用してアプリケーションを実行すると、メインスレッドチェックが自動的に有効になります.
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.長時間実行されるタスク(ネットワークなど)は通常バックグラウンドで実行され、完了処理プログラムを提供して完了信号を発行する.完了したハンドラからUIを読み込んだり更新したりしようとすると、問題が発生する可能性があります.

lettask = URLSession.shared.dataTask(with: url) { (data, response,error)inifletdata = 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.呼び出しをメインスレッドに割り当ててラベルテキストを更新します.

lettask = URLSession.shared.dataTask(with: url) { (data, response,error)inifletdata = data { DispatchQueue.main.async {// Correctself.label.text ="\(data.count)bytes downloaded"} }}task.resume()