appdelegate - Swift 4,必须仅在主线程中使用警告

标签 appdelegate swift4 xcode9

当我在 Xcode 9 中使用 Swift4 时,给了我

UIApplication.delegate must be used from main thread only

.... must be used from main thread only

UI API called from background thread Group

紫色警告。

我的代码;

var appDelegate = UIApplication.shared.delegate as! AppDelegate
public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let prefs:UserDefaults = UserDefaults.standard
var deviceUUID = UIDevice.current.identifierForVendor!.uuidString

警告线是;

  public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext

另一个这样的警告;

 let parameters = [
                        "tel": "\(self.phone.text!)"
                        ] as [String : String]

给予

UITextField.text must be used from main thread only

同样的错误再次..

我该如何修复它?有什么想法吗?

最佳答案

您正在后台队列中进行此调用。要解决此问题,请尝试...

public var context: NSManagedObjectContext

DispatchQueue.main.async {

    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    context = appDelegate.persistentContainer.viewContext        
}

尽管这是一种非常糟糕的方法……您正在使用应用程序委托(delegate)作为全局变量(我们都知道这很糟糕!)

您应该考虑将托管对象上下文从 View Controller 传递到 View Controller ......

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 

    (window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}

等等

关于appdelegate - Swift 4,必须仅在主线程中使用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46218270/

相关文章:

ios - 从 AppDelegate 向 ViewController 的属性添加值

ios - iOS App的AppDelegate中open URL方法的区别

ios - 使用 Firebase 进行身份验证自动登录

ios - 未调用 URLSession 委托(delegate)方法

ios - 没有这样的文件或目录 : 'SwiftyJSON'

xcode - Xcode 9.0.1 及更高版本有 100+ "Class implemented in both MapKit and VectorKit"警告

appdelegate - Apple Watch 应用程序的应用程序委托(delegate)文件相当于什么?

ios - 在 swift 4 中显示 MCBrowserViewController

ios - TabBarController 不会更改选定的索引

ScrollView 下的iOS swift 4 imageview : double tap to zoom out