核心数据似乎不会保存数据

时间:2016-07-13 09:13:01

标签: ios core-data swift2

我想在私有环境中保存一些内容,以便我的UI不被阻止。所以我认为一切正常,但是当我从wifi断开连接并重启应用程序时,它并没有显示任何来自coredata。所以在我看来它并没有保存任何东西,我也找不到原因。

这是我的核心数据设置:

class CoreDataDatabaseService: NSObject {
    // Singleton
    static let sharedInstance = CoreDataDatabaseService()

    // MARK: - Core Data stack

    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "be.donpironet.Gins4u" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
    }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("Model", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
    }()

    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.URLByAppendingPathComponent("Model.sqlite")
        var failureReason = "There was an error creating or loading the application's saved data."
        do {
            try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
        } catch {
            // Report any error we got.
            var dict = [String: AnyObject]()
            dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
            dict[NSLocalizedFailureReasonErrorKey] = failureReason

            dict[NSUnderlyingErrorKey] = error as NSError
            let wrappedError = NSError(domain: "G_COREDATA", 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.
            DDLogError("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
            abort()
        }

        return coordinator
    }()

    lazy var mainContext: 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
    }()

    func privateContext() -> NSManagedObjectContext {
        let managedObjectContext = NSManagedObjectContext(concurrencyType: .PrivateQueueConcurrencyType)
        managedObjectContext.parentContext = self.mainContext

        return managedObjectContext
    }
}

就像你可以看到我的privateContext总是将mainContext作为父。我只在我的私人环境中保存东西,而我的主要背景只显示数据。

let managedContext = CoreDataDatabaseService.sharedInstance.privateContext()

... I create some objects

    do {
                    if managedContext.hasChanges {
                        try managedContext.save()
                        observer.on(.Next("Success"))
                        observer.on(.Completed)
                    }

                } catch let error as NSError  {
                    DDLogError("Could not save \(error), \(error.userInfo)")
                    observer.on(.Error(error))
                }

当我运行这个时,我有wifi,应用程序显示结果,所以NSFetchResultController被触发,所以我猜模型在数据库中,否则这是不可能的(我认为)。

所以谁知道我做错了什么?为什么应用程序没有保存结果(尽管保存操作不会引发错误)

1 个答案:

答案 0 :(得分:0)

我发现了问题。保存子上下文时,还需要保存父上下文。

因此在保存私有上下文后,只需在maincontext上调用save(),一切正常。