核心数据未保留旧值

时间:2019-03-15 05:36:06

标签: swift core-data

当我保存到Core Data并尝试从中读取数据时,只会保留最近保存的值。
其余的是nil,当我尝试将其打印出来时。

在我的.xcdatamodeld中,我的实体名为CD_Cookbook,其属性为name
我不确定自己在做什么错。

func newCookbook(cookbook: String) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    let managedContext = appDelegate.persistentContainer.viewContext

    let entity = NSEntityDescription.entity(forEntityName: "CD_Cookbook", in: managedContext)!
    let item = NSManagedObject(entity: entity, insertInto: managedContext)
    item.setValue(cookbook, forKey: "name")
    do {
        try managedContext.save()
    }
    catch {
        print("did not save cookbook name to core data", error)
    }

    let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CD_Cookbook")
    do {
        let cd = try managedContext.fetch(fetchRequest)
        print(cd)
    }
    catch {
        print("Failed to fetch cookbook names from Core Data", error)
    }
}

1 个答案:

答案 0 :(得分:0)

代替:

let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "CD_Cookbook")

执行此操作:

let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "CD_Cookbook")