核心数据 setValue 似乎覆盖了以前的值

Core Data setValue seem to overWrite previous values

尝试学习 core data 并卡在我设置数据的地方,但是当我尝试获取它时,只返回最后一个元素。我有一种感觉,这是因为 setValue 覆盖了以前的值。

func setData(data: People) {

    let enmployeeEntity = NSEntityDescription.entity(forEntityName: "EmployeesCoreData", in: context)
    let employee = NSManagedObject(entity: enmployeeEntity!, insertInto: context)

    for i in 0...data.people.count - 1 {
        employee.setValue(data.people[i].name, forKey: "name")
        print(data.people[i].name)
    }
}

print 给了我所有十个元素,所以至少我知道它们在那里。

然后当我尝试 fetch 时,我得到的数据是 data.people[i].name 的最后一个元素。

func fetchMyData() {

    do {
        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "EmployeesCoreData")
        let result = try context.fetch(request)

        print(result.count) //Returns 1
        for data in result as! [NSManagedObject] {
            let myDataName = data.value(forKey: "name") as! String
             print("", myDataName)
        }
    } catch {
        let nserror = error as NSError
        print(nserror)
        }
}

知道为什么只显示最后一个 element 吗?如果您需要查看更多代码,请告诉我。

您在 setData 中只创建了一个实体实例,将循环更改为

for i in 0...data.people.count - 1 {
    let employee = NSManagedObject(entity: enmployeeEntity!, insertInto: context)
    employee.setValue(data.people[i].name, forKey: "name")
    print(data.people[i].name)
}