【问题标题】:Accessing Core Data from both container app and extension从容器应用程序和扩展程序访问核心数据
【发布时间】:2017-05-31 18:08:33
【问题描述】:

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

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

【问题讨论】:

  • 您能否告诉我如何将其访问到 imessage 扩展程序中。我想在 MSMessagesAppViewController 中访问。

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


【解决方案1】:
 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
}()

【讨论】:

  • 本质上,Swift 3 的变化是您需要将安全组指向您的存储 url,以便它们都被存储到那个。 (假设您已经在项目功能部分正确设置了应用组)
  • 我已将持久存储(sqlite 文件)保存到一个共享的应用程序组目录,如上。但是,我不知道如何从应用程序扩展中访问持久存储。我找到的所有代码都使用主应用程序中的应用程序委托(扩展中不可用)来获取 ManagedObjectContext。谁能告诉我该怎么做?
  • 有冗余代码。 1 班轮container.persistentStoreDescriptions = ... 将正确设置。上面的 6 行是多余的。无论如何,shouldInferMappingModelAutomaticallyshouldMigrateStoreAutomatically 的默认值已经是 true。
  • @MichaelBremerkamp 我也有同样的问题。你做到了吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-22
  • 2022-08-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-04
  • 1970-01-01
相关资源
最近更新 更多