簡體   English   中英

如何在核心數據Swift 3中使用persistentStore(for:url)

[英]How to use persistentStore(for: url) in core data Swift 3

我正在嘗試執行以下操作:

輕按的小區UITableView細胞然后segue到下一個UIViewController和顯示數據庫的結果。 但是有多個持久性存儲,因此指定的存儲由單元標簽文本指定。

問題是:如何使用方法persistentStore(for: url) 還是有其他方法為fetchRequest指定持久存儲?

這是我的代碼不起作用:

func wordFetchRequest() -> NSFetchRequest<Word> {
    let fr = NSFetchRequest<Word>(entityName: "Word")
    fr.fetchBatchSize = 100

    // Assigning sort descriptors
    let firstLetterSort = NSSortDescriptor(key: #keyPath(Word.firstLetter), ascending: true)
    let spellSort = NSSortDescriptor(key: #keyPath(Word.spell), ascending: true)
    fr.sortDescriptors = [firstLetterSort, spellSort]

    // Get URL of the designated store to fetch
    let libname = (AppDelegate.nameDict as NSDictionary).allKeys(for: nameToFetch).first!

// I'm not sure the following line: which file should I use? I've tried
//.sqlite, .sqlite-shm and .sqlite-wal but none worked.
    let url = AppDelegate.coreDataStack.storeDirectory.appendingPathComponent("\(libname).sqlite-wal")

    // Specify affected store for the fetch request
    var pss = [NSPersistentStore]()
    print(url)

// The following line fails:
    if let ps = coreDataStack.psc.persistentStore(for: url) {
        pss.append(ps)
    } else {

    }

    fr.affectedStores = pss
    print(fr.affectedStores ?? "No stores available.")
    return fr
}

任何幫助都感激不盡。

我不得不處理類似的情況,即我擁有不同的持久性存儲(具體來說,一種類型為NSInMemoryStoreType,而另一種類型為NSSQLiteStoreType

我發現為每個商店創建單獨的持久性存儲協調器和使用這些持久性存儲(如父存儲)創建單獨的管理對象上下文更容易:

這是用iOS 9 swift 3編寫的代碼,因此具有較舊的核心數據堆棧操作,我已經看到了iOS 10 Swift 3 Core數據堆棧,我相信這些方法仍然可以使您了解這里所說的內容:)

這就是你將默認在Coredata堆棧看到,getter方法persistentStoreCoordinator

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
        // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
        // Create the coordinator and store
        let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
        let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
            log.debug(url)
        } catch let error as NSError {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
            dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

            dict[NSUnderlyingErrorKey] = error
            let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
            // Replace this with code to handle the error appropriately.
            // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
            NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }
        catch{

        }
        return coordinator
    }()

重要的聲明是

try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)

如您所見,它將持久性存儲類型指定為Sqlite並將configurationName指定為nil,這意味着默認配置:)

您可以在Coredata中創建多個配置,並在此語句中指定名稱,以便為每個配置創建單獨的持久性存儲協調器:)

您可以在我的博客中查看是否可以使用敏感信息信任核心數據,以了解如何創建多個配置和存儲:)

因此,假設您創建了另一個配置並向其中添加了實體,並將其稱為“ Test1”配置,您將為此創建一個單獨的持久性存儲協調器,

lazy var test1PersistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added 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.
    // Create the coordinator and store
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: "Test1", at: url, options: nil)
        log.debug(url)
    } catch let error as NSError {
        // Report any error we got.
        var dict = [String: AnyObject]()
        dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
        dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?

        dict[NSUnderlyingErrorKey] = error
        let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
        // Replace this with code to handle the error appropriately.
        // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }
    catch{

    }
    return coordinator
}()

現在,您有兩個與兩種不同配置關聯的持久性存儲協調器,只需使用這些持久性存儲協調器作為其父存儲創建兩個托管對象上下文:)

   lazy var managedObjectContext: NSManagedObjectContext = {
        // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
        let coordinator = self.persistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()


    lazy var managedObjectContextForBackTracking : NSManagedObjectContext = {
        let coordinator = self.test1PersistentStoreCoordinator
        var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
        managedObjectContext.persistentStoreCoordinator = coordinator
        return managedObjectContext
    }()

而已 :)

現在,在相應的ManagedObject上下文上運行獲取請求:),確保沒有混亂您的核心數據:)

希望能幫助到你 :)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM