Swift 4 , must be used from main thread only 警告
Swift 4 ,must be used from main thread only warning
当我在 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
}
尽管这是一种非常糟糕的方法……您将 App Delegate 用作全局变量(我们都知道这很糟糕!)
您应该考虑将托管对象上下文从视图控制器传递到视图控制器……
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
(window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}
等等
当我在 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
}
尽管这是一种非常糟糕的方法……您将 App Delegate 用作全局变量(我们都知道这很糟糕!)
您应该考虑将托管对象上下文从视图控制器传递到视图控制器……
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
(window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}
等等