Swift 4,必须仅从主线程使用警告 [英] Swift 4 ,must be used from main thread only warning
问题描述
当我在 Xcode 9
中使用 Swift4
给我
When I using Swift4
in Xcode 9
gives me
UIApplication.delegate 只能在主线程中使用
UIApplication.delegate must be used from main thread only
.... 只能在主线程中使用
.... must be used from main thread only
从后台线程组调用的UI API
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 只能在主线程中使用
UITextField.text must be used from main thread only
又是同样的错误..
我该如何解决?有什么想法吗?
How can I fix it ? Any idea ?
推荐答案
您正在后台队列上进行此调用.要修复,请尝试类似……
You're making this call on a background queue. To fix, try something like…
public var context: NSManagedObjectContext
DispatchQueue.main.async {
var appDelegate = UIApplication.shared.delegate as! AppDelegate
context = appDelegate.persistentContainer.viewContext
}
尽管这是一种非常糟糕的方法……但您将 App Delegate 用作全局变量(我们都知道这很糟糕!)
Although this is a pretty bad way to do this… you're using your App Delegate as a global variable (which we all know is bad!)
您应该考虑将托管对象上下文从视图控制器传递到视图控制器......
You should look at passing the managed object context from view controller to view controller…
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
(window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}
等等
这篇关于Swift 4,必须仅从主线程使用警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!