在Xcode9 中,我們有時可以看到這樣的警告:
Main Thread Checker: UI API called on a background thread: -[UIApplication delegate]
不過金句,系統(tǒng)并不會必然發(fā)生crash,但是出現(xiàn)的多了逗物,就會偶發(fā)crash了搬卒,就變成一個很難復(fù)現(xiàn)的bug了。
這種情形多發(fā)生在種block回調(diào)翎卓、多線程處理契邀、網(wǎng)絡(luò)處理等場景;
這個警告有點(diǎn)像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.
當(dāng)然兩個警告應(yīng)該不是同一類型失暴,但都是同多線程/主線程有關(guān)坯门;
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.
官方文檔寫的都非常詳細(xì),不再復(fù)述锐帜。
需要注意的是:
語法:[UIApplication delegate]
也是要放到Main Thread中的,不然也會報警告畜号;
Main Thread Checker 在XCode 中有開關(guān):
Edit schemes > Diagnostics > Runtime API Checking:
例如下圖:
最后來一句廢話:
當(dāng)App端系統(tǒng)開始變得越來越復(fù)雜的時候缴阎,這時候一般也會有越來越多的異步操作,異步操作的結(jié)果又要回調(diào)到界面主線程當(dāng)中简软,異步操作再結(jié)合block的回調(diào)蛮拔,又會讓情況變得更加復(fù)雜。此時就需要在編寫代碼時盡量遵守一些經(jīng)過驗(yàn)證的模式痹升,避免一不留神把坑埋進(jìn)去建炫。