Xcode 9 的 Main Thread Checker

開發 iOS App 時,有些事情,我們一定得在 main thread 做,比方 UI 相關的程式碼。Xcode 9 為了幫助我們,推出全新的 Main Thread Checker,把所有不該在 background thread 執行的壞程式通通抓出來 !

Main Thread Checker 預設是打開的,可從 App Scheme 的 Diagnostics 頁面勾選 Main Thread Checker 是否啟動。

當 Main Thread Checker 啟動時,以下程式碼將造成 App 閃退,因為我們在背景設定 image view 的圖片。

解決的方法很簡單,只要利用 DispatchQueue.main.async,切換到 main thread 執行即可。

override func viewDidLoad() {    super.viewDidLoad()    let urlStr = "https://wakelandtheatre.files.wordpress.com/2013/11/final-poster.jpg"    let url = URL(string: urlStr)    let task = URLSession.shared.dataTask(with: url!) { (data, response , error) in        if let data = data, let image = UIImage(data: data) {            DispatchQueue.main.async {                self.imageView.image = image            }        }    }    task.resume()}
)

彼得潘的 iOS App Neverland

Written by

彼得潘的 Swift 程式設計入門,App程式設計入門作者,彼得潘的iOS App程式設計入門,文組生的iOS App程式設計入門講師,http://apppeterpan.strikingly.com

彼得潘的 Swift iOS App 開發問題解答集

彼得潘和學生們在開發 iOS App 路上曾經解決的問題集

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade