简体   繁体   中英

Universal context for CoreData

I use NSPersistentContainer as a dependency in my classes. I find this approach quite useful, but there is a dilemma: I don't know in which thread my methods will be called. I found a very simple solution for this

extension NSPersistentContainer {
    func getContext() -> NSManagedObjectContext {
        if Thread.isMainThread {
            return viewContext
        } else {
            return newBackgroundContext()
        }
    }
}

Looks wonderful but I still have a doubt is there any pitfalls? If it properly works, why on earth Core Data confuses us with its contexts?

It's OK as long as you can live with its inherent limitations, ie

  • When you're on the main queue, you always want the viewContext , never any other one.
  • When you're not on the main queue, you always want to create a new, independent context.

Some drawbacks that come to mind:

  • If you call a method that has an async completion handler, that handler might be called on a different queue. If you use this method, you might get a different context than when you made the call. Is that OK? It depends what you're doing in the handler.
  • Changes on one background context are not automatically available in other background contexts, so you run the risk of having multiple contexts with conflicting changes.
  • The method suggests a potential carelessness about which context you're using. It's important to be aware of which context you're using, because managed objects fetched on one can't be used with another. If your code just says, hey give me some context, but doesn't track the contexts properly, you increase the chance of crashes from accidentally crossing contexts.

If your non-main-queue requirements match the above, you're probably better off using the performBackgroundTask(_:) method on NSPersistentContainer . You're not adding anything to that method here.

[W]hy on earth Core Data confuses us with its contexts?

Managed object contexts are a fundamental part of how Core Data works. Keeping track of them is therefore a fundamental part of having an app that doesn't corrupt its data or crash.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM