Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing Core Data from both container app and extension

I'm developing app and share extension and trying to use core data. But when I'm inserting items in the extension those items only visible in extension but not from container app (e.g I perform NSFetchRequest from app and getting zero items but in app I got >0). I'm using the following code for getting the persistent container:

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "appname")
    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error {

            fatalError("Unresolved error \(error)")
        }
    })
    return container
}()

Also, the target member ship for appname.xcdatamodeld is checked for both app and extension. How to share core data correctly for both container app and extension?

like image 204
mirt Avatar asked Jan 16 '17 20:01

mirt


1 Answers

 lazy var persistentContainer: NSPersistentContainer = {
    /*
     The persistent container for the application. This implementation
     creates and returns a container, having loaded the store for the
     application to it. This property is optional since there are legitimate
     error conditions that could cause the creation of the store to fail.
     */
    let container = NSPersistentContainer(name: "xx")

    let appName: String = "xx"
    var persistentStoreDescriptions: NSPersistentStoreDescription

    let storeUrl =  FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.xx.xx.container")!.appendingPathComponent("xx.sqlite")


    let description = NSPersistentStoreDescription()
    description.shouldInferMappingModelAutomatically = true
    description.shouldMigrateStoreAutomatically = true
    description.url = storeUrl

    container.persistentStoreDescriptions = [NSPersistentStoreDescription(url:  FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.xxx.xx.container")!.appendingPathComponent("xx.sqlite"))]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()
like image 182
Garrett Cox Avatar answered Sep 18 '22 12:09

Garrett Cox