从容器应用程序和扩展程序访问核心数据 [英] Accesing Core Data from both container app and extension

查看:220
本文介绍了从容器应用程序和扩展程序访问核心数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm developing app and share extension and trying to use core data. But when i'm insertin 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
}()

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

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?

推荐答案

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

这篇关于从容器应用程序和扩展程序访问核心数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆