Swift 4,必须仅从主线程警告中使用

Swi*_*per 28 appdelegate swift4 xcode9

我用Swift4的时候Xcode 9给了我

UIApplication.delegate只能从主线程使用

....必须仅从主线程使用

从后台线程组调用的UI API

紫色警告.

我的代码;

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
Run Code Online (Sandbox Code Playgroud)

警告线是;

  public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
Run Code Online (Sandbox Code Playgroud)

像这样的另一个警告;

 let parameters = [
                        "tel": "\(self.phone.text!)"
                        ] as [String : String]
Run Code Online (Sandbox Code Playgroud)

UITextField.text只能从主线程使用

同样的错误..

我该如何解决?任何的想法 ?

Ash*_*lls 59

您正在后台队列上进行此调用.要解决,尝试类似......

public var context: NSManagedObjectContext

DispatchQueue.main.async {

    var appDelegate = UIApplication.shared.delegate as! AppDelegate
    context = appDelegate.persistentContainer.viewContext        
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一个非常糟糕的方法...你正在使用你的App Delegate作为全局变量(我们都知道这很糟糕!)

您应该查看将托管对象上下文从视图控制器传递到视图控制器...

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: 

    (window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext
}
Run Code Online (Sandbox Code Playgroud)

等等