Swift 4,只能在主线程中使用警告 [英] Swift 4 ,must be used from main thread only warning
问题描述
当我在Xcode 9
中使用Swift4
时给我
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屋!