Xcode Main Thread Checker

在Xcode9 中,我們有時可以看到這樣的警告:

Main Thread Checker: UI API called on a background thread: -[UIApplication delegate]

不過,系統并不會必然發生crash,但是出現的多了,就會偶發crash了,就變成一個很難復現的bug了。
這種情形多發生在種block回調、多線程處理、網絡處理等場景;

這個警告有點像Xcode8中的下面這個警告:

This application is modifying the autolayout engine from a background thread after the engine was accessed from the main thread. This can lead to engine corruption and weird crashes.

當然兩個警告應該不是同一類型,但都是同多線程/主線程有關;

Main Thread Checker:

官方文檔見:
https://developer.apple.com/documentation/code_diagnostics/main_thread_checker

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.

官方文檔寫的都非常詳細,不再復述。
需要注意的是:
語法:[UIApplication delegate]
也是要放到Main Thread中的,不然也會報警告;

Main Thread Checker 在XCode 中有開關:
Edit schemes > Diagnostics > Runtime API Checking:

例如下圖:

2C541143-D830-409E-94D2-DD967BB62A2F.png

最后來一句廢話:

當App端系統開始變得越來越復雜的時候,這時候一般也會有越來越多的異步操作,異步操作的結果又要回調到界面主線程當中,異步操作再結合block的回調,又會讓情況變得更加復雜。此時就需要在編寫代碼時盡量遵守一些經過驗證的模式,避免一不留神把坑埋進去。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容