当我在 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/