DispatchQueue:在非主线程上无法使用asCopy = NO调用

Ami*_*mit 20 grand-central-dispatch swift dispatch-queue swift4.2

UIAlertController将主线程呈现为:

class HelperMethodClass: NSObject {

    class func showAlertMessage(message:String, viewController: UIViewController) {
        let alertMessage = UIAlertController(title: "", message: message, preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "Ok", style: .cancel)

        alertMessage.addAction(cancelAction)

        DispatchQueue.main.async {
            viewController.present(alertMessage, animated: true, completion: nil)
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我从任何方面调用方法UIViewController:

HelperMethodClass.showAlertMessage(message: "Any Message", viewController: self)
Run Code Online (Sandbox Code Playgroud)

我正确地得到了输出.

但在控制台中,我收到以下消息:

[Assert]在非主线程上无法使用asCopy = NO调用.

我在这里做错了什么,或者我可以忽略这个消息?

编辑

感谢@NicolasMiari:

添加以下代码不会显示任何消息:

DispatchQueue.main.async {
    HelperMethodClass.showAlertMessage(message: "Any Message", viewController: self)
}
Run Code Online (Sandbox Code Playgroud)

之前它在控制台中显示消息的原因是什么?

Ily*_*bet 41

您应该从showAlertMessage主队列中调用所有代码:

class func showAlertMessage(message:String, viewController: UIViewController) {
    DispatchQueue.main.async {
        let alertMessage = UIAlertController(title: "", message: message, preferredStyle: .alert)

        let cancelAction = UIAlertAction(title: "Ok", style: .cancel)

        alertMessage.addAction(cancelAction)

        viewController.present(alertMessage, animated: true, completion: nil)
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 为什么需要这个? (3认同)
  • @Jeff 此视频未提供问题的答案。我也对为什么我们需要在主线程上实例化 UIAlertController 感兴趣。 (3认同)
  • @nonolays观看此视频。https://www.youtube.com/watch?v=iTcq6L-PaDQ (2认同)
  • @VinGazoil 任何时候更新 UI 时,您都需要位于主线程上。我不能说为什么 UIAlertController 还没有在主线程上,但 print(Thread.isMainThread) 会告诉你是否在主线程上。 (2认同)
  • 我仍然不清楚为什么 UIAlertController 的创建需要在主线程中......如果没有这个,我们的行为就会变得非常奇怪(人们无法点击屏幕的随机部分)。 (2认同)
  • 我知道这很奇怪,但是任何视图控制器都应该在主线程上实例化,而不仅仅是在演示时实例化。在呈现之前的任何时间,视图控制器都可能加载其视图甚至修改它们,以响应某些公共方法的使用。 (2认同)