Swift 4, must be used only from the main thread

When I use Swift4 in Xcode 9 , gives me

UIApplication.delegate should only be used from the main thread

.... should only be used from the main thread

UI API called from a background thread Group

Violet warning.

My codes

 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 

Warning line:

  public var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 

Another warning like this;

  let parameters = [ "tel": "\(self.phone.text!)" ] as [String : String] 

Gives

UITextField.text should be used only from the main thread

Repeat the same error.

How can i fix this? Any idea?

+4
source share
1 answer

You are calling this call in the background. To fix, try something like ...

 public var context: NSManagedObjectContext DispatchQueue.main.async { var appDelegate = UIApplication.shared.delegate as! AppDelegate context = appDelegate.persistentContainer.viewContext } 

Although this is a pretty bad way to do this ... you use your App Delegate as a global variable (which we all know is bad!)

You should look at passing the context of the managed entity from the view controller to view the controller ...

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: (window?.rootViewController as? MyViewController)?.moc = persistentContainer.viewContext } 

etc.

+18
source

Source: https://habr.com/ru/post/1271792/


All Articles