从容器应用程序和扩展程序访问核心数据

时间:2017-01-16 20:10:36

标签: ios core-data ios10 ios-app-extension

我正在开发应用和共享扩展并尝试使用核心数据。但是,当我在扩展程序中插入项目时,这些项目只能在扩展程序中看到,但不能从容器应用程序中看到(例如,我从应用程序执行NSFetchRequest并获得零项目,但在应用程序中我得到> 0)。 我使用以下代码获取持久性容器:

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
}()

此外,还会针对app和扩展程序检查appname.xcdatamodeld的目标成员。 如何正确分享容器应用和扩展的核心数据?

1 个答案:

答案 0 :(得分:19)

 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
}()