2017-01-16 3 views
6

アプリケーションを開発して拡張機能を共有し、コアデータを使用しようとしています。しかし、私が拡張機能のアイテムを挿入しているときに、それらのアイテムは拡張機能で表示されますが、コンテナアプリからは表示されません(たとえば、アプリから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のターゲットメンバーシップは、アプリや拡張機能の両方のためにチェックされています。 コンテナのアプリと拡張機能の両方でコアデータを正しく共有するにはどうすればよいですか?

答えて

13
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 
}() 
+0

あなたは、彼らは両方ともされているように、お店のURLとしてsecuritygroupを指す必要があるということですそれに格納されます。 (すでにプロジェクト機能の部分に適切にアプリケーショングループを設定していると仮定します) –

+0

永続ストア(sqliteファイル)を上記のような共有アプリケーショングループディレクトリに保存しました。ただし、アプリの拡張機能から永続ストアにアクセスする方法を理解できません。私が見つけたすべてのコードは、ManagedObjectContextを取得するためにメインアプリケーションからアプリケーションデリゲート(拡張機能では利用できません)を使用します。誰も私にこのことを教えてもらえますか? –

-1

拡張機能はメインアプリと同じデータストアにアクセスできません。メインアプリはNSUSerDeafults.initWithSuitNameと共有データストアを作成する必要があります

基本的に何がスウィフト3のために変更されました
NSUserDefaults * sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"groupName"]; 
関連する問題