美文网首页iOS开发小抄
Xcode Main Thread Checker

Xcode Main Thread Checker

作者: zhangyin | 来源:发表于2017-08-30 21:08 被阅读1132次

    在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的回调,又会让情况变得更加复杂。此时就需要在编写代码时尽量遵守一些经过验证的模式,避免一不留神把坑埋进去。

    相关文章

      网友评论

        本文标题:Xcode Main Thread Checker

        本文链接:https://www.haomeiwen.com/subject/zbnxjxtx.html