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

我正在开发应用程序和共享扩展,并尝试使用核心数据。 但是,当我插入扩展项中的项目,这些项目只在扩展中可见,但不是从容器应用程序(例如,我从应用程序执行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的目标成员发货都将同时针对应用和扩展程序进行检查。 如何正确共享容器应用程序和扩展的核心数据?

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

该扩展将无法访问相同的数据存储在主应用程序。 主应用程序需要使用NSUSerDeafults.initWithSuitName创build共享数据存储

 NSUserDefaults * sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"groupName"];