应用程序从后台线程修改自动布局引擎

app modifying the autolayout engine from a background thread

我几乎完成了将我的 iOS 应用程序迁移到 Swift 3.0。 但是我仍然有几个案例类似于下面的案例。 我已经能够通过将有问题的代码放在主线程上来解决其中的大部分问题。

在其他一些情况下,我无法确定我的代码的哪一部分在错误的线程上执行。我收到这样一条消息:

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.
 Stack:(
    0   CoreFoundation                      0x000000018765a1d8 <redacted> + 148
    1   libobjc.A.dylib                     0x000000018609455c objc_exception_throw + 56
    2   CoreFoundation                      0x000000018765a108 <redacted> + 0
    3   Foundation                          0x0000000188241ea4 <redacted> + 192
    ....................
    16  libsystem_pthread.dylib             0x00000001866eece4 <redacted> + 200
    17  libsystem_pthread.dylib             0x00000001866ee378 pthread_mutex_lock + 0
    18  libsystem_pthread.dylib             0x00000001866edda4 start_wqthread + 4
)

是否有一些特殊的技术(使用调试器或 ?? 时的选项)我可以用来跟踪程序所遵循的路径,看看发生了什么?

我认为没有任何其他内置工具可用于调试此类崩溃,因为它是从 运行 代码修改 AutoLayout UI elements/constraints 的代码宁后台线程或完成处理程序。默认情况下,后台线程中的所有完成处理程序 运行。您需要使用 GCD 更新完成处理程序块中的 UI 元素。

显然您正在对后台线程进行一些 UI 更新。在没有看到您的代码的情况下无法准确预测位置。

这些是可能发生的一些情况:-

  1. 您可能正在后台线程上执行某些操作但未使用。由于在同一函数中,这段代码更容易被发现。

    DispatchQueue.main.async { // do UI update here }
    
  2. 调用 func 在后台线程上执行 Web 请求调用,其完成处理程序调用其他 func 执行 ui 更新。

要解决此问题,请尝试检查您在 webrequest 调用后更新了 UI 的代码。

 // Do something on background thread
DispatchQueue.global(qos: .userInitiated).async {
   // update UI on main thread
   DispatchQueue.main.async {
                // Updating whole table view
                self.myTableview.reloadData()
            }
}