Search code examples
iosswiftcore-datansfetchrequest

Core Data setValue seem to overWrite previous values


Trying to learn core data and get stuck on this thing where I set the data, but when I try to fetch it, only the last element is returned. I have a feeling this is because setValue overWrites the previous values.

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)
    }
}

The print gives me all ten elements, so at least I know that they're there.

Then when I try to fetch the data all I get is the very last element of 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)
        }
}

Any idea why only the last element is shown? Let me know if you need to see more code.


Solution

  • You are creating only one instance of your entity in setData, change the loop to

    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)
    }