从后台线程调用 UIKit 时发出警告 [英] Warn on calls to UIKit from background threads

查看:20
本文介绍了从后台线程调用 UIKit 时发出警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS 的 UIKit 不是线程安全的,让我们称之为众所周知的事实.我知道规则,我很小心,但我仍然会被咬 - 而且时不时地导致的崩溃与对 UIKit 的违规后台调用相距甚远,从而使追踪问题成为一种不那么快乐的体验.

iOS's UIKit is not thread-safe, let us call this fact well known. I know the rule, I'm careful, but I still get bitten - and every now and then the resulting crash is far enough removed from the offending background call into UIKit to make tracking down the problem a less than joyeus experience.

这个问题似乎很容易解决——让 UIKit 类/方法在从后台线程调用时发出警告,至少作为调试功能.据我所知,iOS 不提供任何此类功能.当然,可以通过在此类调用之前添加某种形式的断言来手动实现相同的效果,但这种解决方案并不是最优雅的,而且还存在与原始问题相同的弱点,即程序员容易健忘.

This problem seems like it could be easy to solve - have UIKit classes/methods warn when they are invoked from a background thread, at least as a debug feature. As far as I'm aware, iOS does not provide any such feature. Of course one could achieve the same effect manually by having some form of assertions precede such calls, but this solution is not the most elegant and in addition suffers from the same weakness as the original problem, namely that programmers are prone to forgetfulness.

有没有人有更优雅的解决方案?您如何在项目中处理这个问题?

Does anyone have a more elegant solution? How do you deal with this problem in your projects?

(注意:这个问题是相关的,但不是很明确.有人想知道)

(Note: this question is related, but not quite as explicit. One is left wondering)

更新:Andrew 的答案是我当时正在寻找的解决方案,但请注意,至少从 Xcode 9 开始,这现在由 xcode/ios 提供.例如,添加以下代码:

UPDATE: Andrew's answer is the solution I was looking for at the time, however note that at least as of Xcode 9 this is now provided by xcode/ios. For instance, adding this code:

DispatchQueue.global().async {
        print(self.view.frame)
    }

UIView 的 viewDidLoad 方法会在 Xcode 中内联生成运行时警告 UIView.frame 必须仅在主线程中使用,并在控制台打印一条消息:主线程检查器:UI API在后台线程上调用:-[UIView 框架]

To a UIView's viewDidLoad method produces a runtime warning inline in Xcode UIView.frame must be used from the main thread only and a message printed to the console: Main Thread Checker: UI API called on a background thread: -[UIView frame]

推荐答案

此代码(只需添加到项目并在没有 ARC 的情况下编译此文件)导致 UIKit 访问主线程之外的断言:https://gist.github.com/steipete/5664345

This code (just add to project and compile this file without ARC) causes assertions on UIKit access outside of the main thread: https://gist.github.com/steipete/5664345

我刚刚用它在我刚刚拾取的一些代码中拾取了许多 UIKit/主线程问题.

I've just used it to pickup numerous UIKit/main thread issues in some code I've just picked up.

这篇关于从后台线程调用 UIKit 时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆