Ios UIApplication.delegate只能从主线程使用

Ios UIApplication.delegate只能从主线程使用,ios,swift,xcode,thread-safety,uiapplication,Ios,Swift,Xcode,Thread Safety,Uiapplication,我的应用程序代理中有以下代码作为在其他ViewController中使用CoreData的快捷方式: let ad = UIApplication.shared.delegate as! AppDelegate let context = ad.persistentContainer.viewContext 但是,我现在收到错误消息: “从后台线程调用UI API”和“UIApplication.delegate只能从主线程使用” 我在后台使用CoreData,但这是我第一次看到此错误消息。有

我的应用程序代理中有以下代码作为在其他ViewController中使用CoreData的快捷方式:

let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext
但是,我现在收到错误消息:

“从后台线程调用UI API”和“UIApplication.delegate只能从主线程使用”

我在后台使用CoreData,但这是我第一次看到此错误消息。有人知道这里发生了什么吗

更新:我尝试将其移动到appDelegate类内部,并使用以下代码-

let dispatch = DispatchQueue.main.async {
    let ad = UIApplication.shared.delegate as! AppDelegate
    let context = ad.persistentContainer.viewContext
}
现在,我无法再访问
AppDelegate
之外的ad和上下文变量。有什么我遗漏的吗?

在Swift中引用此()(用于您的查询解决方案)

带编辑:(声明广告和上下文的正确位置在哪里?我是否应该在主分派中的ViewController中声明它们)
变量的位置(ad和上下文)声明定义了它的范围。您需要决定这些变量的作用域。您可以将它们声明为项目级或应用程序级(全局)、类级或特定的函数级。 如果要在其他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   

    })

看到这一点,我使用的是swift,而不是客观-CI猜测我的问题是,在哪里正确地声明广告和上下文?我应该在主调度的ViewController中声明这些吗?@LFHS尝试回答更新。太棒了,这解决了问题,谢谢。在处理广告和上下文时,我是否需要执行
if let
,因为它们现在是可选的?或者我可以假设它们不会为零吗?如果您使用
可选声明,如
var-ad:AppDelegate?
,那么您应该使用
If-let
从variabel
ad
获取值,但我隐式地将它们展开。当我访问它们时,它们是否有可能为零,从而使我的应用程序崩溃?不隐式地展开它们会更好吗?是的,这取决于条件,您可以围绕这段代码进行设置。您是否为此代码块设置了任何条件。我认为一定有一个条件,因为您可能正在使用数据库操作,并且作为数据库操作的成功结果,这些变量被初始化。所以,如果数据库操作失败,这些变量可能保持为零。检查你的代码和状态。谢谢,我理解。基本上,如果应用程序没有在主调度中运行,我不能使用coreData?
   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   

    })