App Extension Programming Guide on sharing Core Data context with the main app

Viewed 926

There is no documentation or sample code explaining if we can share the viewContext with the app extension or not.

AFAK, the app and the extension run in different processes and we should NOT share moc with another process/thread. I should not share the viewContext the containing app is using with the app extension.

So should we create another viewContext to use in app extension(? but NSPersistentContainer only provides one viewContext) or use a background context in app extension(???)

While an extension is running, it communicates directly only with the host app. There is no direct communication between a running extension and its containing app; typically, the containing app isn’t even running while its extension is running. In addition, the containing app and the host app don’t communicate at all.

So since they all run in different processes, so maybe (???) I can come to the conclusion that when the app extension ask for the viewContext, and when the containing app ask for the viewContext, the 2 viewContext(s) are actually distinct instances?

class Master {
    static let shared: Master = Master()

    lazy var persistentContainer: CCPersistentContainer = {
        let container = CCPersistentContainer(name: "xt")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })
        return container
    }()

    private var _backgroundContext: NSManagedObjectContext!
    var backgroundContext: NSManagedObjectContext {
        if _backgroundContext == nil {
            _backgroundContext = persistentContainer.newBackgroundContext()
        }
        return _backgroundContext
    }

    var viewContext: NSManagedObjectContext {
        return persistentContainer.viewContext
    }

    func saveContext() {
        let context = persistentContainer.viewContext
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    }
}

---- More On How To Sync Data Across Processes ----

1. WWDC 15: 224_hd_app_extension_best_practices

This WWDC session talks about how to post notification x processes.

2. NSMergePolicy

A policy object that you use to resolve conflicts between the persistent store and in-memory versions of managed objects.

3. WWDC 17: 210_hd_whats_new_in_core_data

4. UserDefaults(suiteName: AppGroups.primary)!

1 Answers
Related