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

viewContext is not getting saved in the database (app.sqlite)

我使用 NSPersistanceContainer 创建了一个应用程序来保存学生的详细信息,当我从 JSON 获取数据并保存到数据库时,当时我得到的获取结果计数 > 0 . 如果我重新启动应用程序,获取结果计数 returns 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)")
            }
        }
    })
}

当我保存到数据库时,上下文不为空,当我检查 sqlite 文件时,table 为空。没有得到我身边缺少的东西。

没有数据被插入到 SQL 文件中

我认为 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
})

问题出在 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)")
        }
    }
}