ios – UIApplication.delegate必须仅在主线程中使用[复制]

前端之家收集整理的这篇文章主要介绍了ios – UIApplication.delegate必须仅在主线程中使用[复制]前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
参见英文答案 > -[UIApplication delegate] must be called from main thread only2个
我在我的app delegate中有以下代码作为在我的其他viewControllers中使用CoreData的快捷方式:
  1. let ad = UIApplication.shared.delegate as! AppDelegate
  2. let context = ad.persistentContainer.viewContext

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

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

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

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

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

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

解决方法

在Swift中引用此( -[UIApplication delegate] must be called from main thread only)(用于查询解析)
  1. DispatchQueue.main.async(execute: {
  2.  
  3. // Handle further UI related operations here....
  4. //let ad = UIApplication.shared.delegate as! AppDelegate
  5. //let context = ad.persistentContainer.viewContext
  6.  
  7. })

使用编辑:(声明广告和上下文的正确位置在哪里?我应该在主调度中的viewControllers中声明这些)
变量位置(广告和上下文)声明定义了它的范围.您需要确定这些变量的范围.您可以将它们声明为项目或应用程序级别(全局),类级别或特定此功能级别.
如果要在其他ViewControllers中使用这些变量,则使用公共/开放/内部访问控制将其声明为全局或类级别.

  1. var ad: AppDelegate! //or var ad: AppDelegate?
  2. var context: NSManagedObjectContext! //or var context: NSManagedObjectContext?
  3.  
  4.  
  5. DispatchQueue.main.async(execute: {
  6.  
  7. // Handle further UI related operations here....
  8. ad = UIApplication.shared.delegate as! AppDelegate
  9. context = ad.persistentContainer.viewContext
  10.  
  11. //or
  12.  
  13. //self.ad = UIApplication.shared.delegate as! AppDelegate
  14. //self.context = ad.persistentContainer.viewContext
  15.  
  16. })

猜你在找的iOS相关文章