2017-01-16 31 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

本質上發生了什麼變化的斯威夫特3是你需要指向securitygroup爲您的商店的網址,讓他們都幸福存儲到那。 (假設您已經在項目功能部分中正確設置了應用程序組) –

+0

我已經將持久性存儲(sqlite文件)保存到上面的共享應用程序組目錄中。但是,我無法弄清楚如何從應用程序擴展中訪問持久存儲。我找到的所有代碼都使用主應用程序中的應用程序委託(不可用於擴展中)來獲取ManagedObjectContext。誰能告訴我如何做到這一點? –

-1

擴展將無法訪問與主應用程序相同的數據存儲。主要的應用程序將需要創建一個共享數據存儲與NSUSerDeafults.initWithSuitName

NSUserDefaults * sharedUserDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"groupName"]; 
相關問題