viewContext未保存在数据库(app.sqlite)SWIFT中

时间:2017-10-28 14:09:16

标签: ios swift core-data persistence

我使用NSPersistanceContainer创建了一个应用程序以保存学生的详细信息,同时我从json获取数据并保存到数据库,此时我获取获取结果计数> 0.如果我重新启动应用程序,则获取结果计数返回0.

lazy var persistentContainer: NSPersistentContainer = {

    let container = NSPersistentContainer(name: "Students_dev")

    let storeURL = try! FileManager
        .default
        .url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        .appendingPathComponent("Students_dev.sqlite")
    print("URL :",storeURL)

    let storeDescription = NSPersistentStoreDescription(url: storeURL)
    storeDescription.shouldMigrateStoreAutomatically = true
    storeDescription.shouldMigrateStoreAutomatically = true
    container.viewContext.automaticallyMergesChangesFromParent = true
    container.persistentStoreDescriptions = [storeDescription]

    container.loadPersistentStores(completionHandler: { (storeDescription, error) in
        if let error = error as NSError? {
            fatalError("Unresolved error \(error), \(error.userInfo)")
        }
    })
    return container
}()

// MARK: - Core Data Saving support

func saveContext (context: NSManagedObjectContext) {

   persistentContainer.performBackgroundTask({ (context) in
        if context.hasChanges {
            do {
                try context.save()
            } catch {
                let nserror = error as NSError
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        }
    })
}

当我保存到db时,上下文不为空,当我检查sqlite文件时表是空的。我没有从我这里得到什么。

没有数据插入SQL文件 screenshot of sql log

2 个答案:

答案 0 :(得分:0)

我认为CoreData警告的原因在于这行代码:

container.viewContext.automaticallyMergesChangesFromParent = true

您在加载商店之前访问viewContext。尝试在加载持久性存储完成块中移动该行:

container.loadPersistentStores(completionHandler: { (storeDescription, error) in
    if let error = error as NSError? {
        fatalError("Unresolved error \(error), \(error.userInfo)")
    }
    container.viewContext.automaticallyMergesChangesFromParent = true
})

答案 1 :(得分:0)

问题出在saveContext函数上,上下文没有被保存到核心数据" persistentContainer.performBackgroundTask ",当我删除它时它工作正常。

代码

func saveContext (context: NSManagedObjectContext) {

    if context.hasChanges {
        do {
            try context.save()
        } catch {
            let nserror = error as NSError
            fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
        }
    }
}