UIApplication.delegate 只能在主线程中使用

UIApplication.delegate must be used from main thread only

我的应用委托中有以下代码作为在我的其他视图控制器中使用 CoreData 的快捷方式:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext

但是,我现在收到错误消息:

"UI API called from background thread" and "UIApplication.delegate must be used from main thread only".

当我的应用程序在后台运行时,我正在使用 CoreData,但这是我第一次看到此错误消息。有人知道这里发生了什么吗?

更新:我尝试将其移入 appDelegate class 本身,并使用以下代码 -

let dispatch = DispatchQueue.main.async {
    let ad = UIApplication.shared.delegate as! AppDelegate
    let context = ad.persistentContainer.viewContext
}

现在,我无法再访问 AppDelegate 之外的广告和上下文变量。有什么我想念的吗?

参考 Swift 中的这个 ()(用于您的查询解析)

    DispatchQueue.main.async(execute: {

      // Handle further UI related operations here....
      //let ad = UIApplication.shared.delegate as! AppDelegate
      //let context = ad.persistentContainer.viewContext   

    })

编辑: (声明广告和上下文的正确位置在哪里?我应该在主调度的视图控制器中声明它们吗)
变量(广告和上下文)声明的位置定义了它的范围。您需要决定这些变量的范围是什么。您可以将它们声明为项目或应用程序级别(全局)、class 级别或特定的此功能级别。 如果您想在其他 ViewController 中使用这些变量,请在全局或 class 级别使用 public/open/internal 访问控制声明它。

   var ad: AppDelegate!    //or var ad: AppDelegate?
   var context: NSManagedObjectContext!    //or var context: NSManagedObjectContext?


   DispatchQueue.main.async(execute: {

      // Handle further UI related operations here....
      ad = UIApplication.shared.delegate as! AppDelegate
      context = ad.persistentContainer.viewContext   

      //or 

      //self.ad = UIApplication.shared.delegate as! AppDelegate
      //self.context = ad.persistentContainer.viewContext   

    })