4

I have a function that gets the context for storing to Core Data. I have it for a few view controllers, however I am getting an error.

private class func getContext() -> NSManagedObjectContext {
    let appDelegate = UIApplication.shared.delegate as! AppDelegate       
    return appDelegate.weatherPersistentContainer.viewContext
}

However I get an error about accessing UI API being called from a background thread.

rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

4

As you see from the error, you can't call UIApplication.shared from a background thread. Since you don't want to have to wrap every call to our getContext method in DispatchQueue.main.async, you can update your getContext method to do the necessary wrapping as needed:

private class func getContext() -> NSManagedObjectContext {
    let appDelegate: AppDelegate
    if Thread.current.isMainThread {
        appDelegate = UIApplication.shared.delegate as! AppDelegate
    } else {
        appDelegate = DispatchQueue.main.sync {
            return UIApplication.shared.delegate as! AppDelegate
        }
    }
    return appDelegate.weatherPersistentContainer.viewContext
}

This code ensures that UIApplication.shared is only called on the main queue, even if getContext is called from a background thread. The nice part is that the result is returned on the original thread.

rmaddy
  • 314,917
  • 42
  • 532
  • 579