UIApplication.delegate只能从主线程使用

LFH*_*FHS 10 xcode thread-safety uiapplication ios swift

我在我的app delegate中有以下代码作为在我的其他viewControllers中使用CoreData的快捷方式:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)

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

"从后台线程调用UI API"和"UIApplication.delegate必须仅从主线程使用".

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

更新:我试图在appDelegate类本身内移动它,并使用以下代码 -

let dispatch = DispatchQueue.main.async {
    let ad = UIApplication.shared.delegate as! AppDelegate
    let context = ad.persistentContainer.viewContext
}
Run Code Online (Sandbox Code Playgroud)

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

Kru*_*nal 5

在Swift中,使用ref对此(-[UIApplication委托]仅可从主线程调用)(用于查询解析)

    DispatchQueue.main.async(execute: {

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

    })
Run Code Online (Sandbox Code Playgroud)

使用edit :( 在哪里声明广告和上下文的正确位置?我应该在主调度器的viewControllers中声明它们)
变量(广告和上下文)声明的位置定义其范围。您需要确定这些变量的范围。您可以将它们声明为项目或应用程序级别(全局),类级别或特定的此功能级别。如果要在其他ViewController中使用这些变量,请使用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   

    })
Run Code Online (Sandbox Code Playgroud)