当前位置:  开发笔记 > 数据库 > 正文

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

如何解决《从容器应用程序和扩展程序访问核心数据》经验,为你挑选了1个好方法。

我正在开发应用程序并共享扩展并尝试使用核心数据.但是当我在扩展中插入项目时,这些项目仅在扩展中可见但不是从容器应用程序中可见(例如,我从应用程序执行NSFetchRequest并获得零项目,但在app中我得到> 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
}()

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



1> Garrett Cox..:
 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
}()


有多余的代码。1个线性`container.persistentStoreDescriptions = ...`将正确设置。上面的6条线是多余的。无论如何,“ shouldInferMappingModelAutomatically”和“ shouldMigrateStoreAutomatically”的默认值已经为true。
推荐阅读
手机用户2502852037
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有