将多个数据条目保存到CoreData中

时间:2016-02-18 07:48:06

标签: core-data swift2 xcode7

我尝试在CoreData中填充我的实体以获取新应用。我创建了一个名为initializeDB()的新函数,它为实体设置新值,然后调用save()函数(当然在do try块中)。然而事实证明,实际上只保存了最后一个实体。我很好奇,知道为什么会这样。我知道只有最后一个被保存,因为我做了一个提取,只看到最后一个被返回。

        date = myTimeZoneDateFormatter1.dateFromString("2016-02-03")!
        entity.setValue("3.1", forKey: "distanceOfRun")
        entity.setValue(date, forKey: "dateOfRun")
        do{
            try moc.save()
            print("save was successful")
        }
        catch{

            print("Entry was not saved")        }

        date = myTimeZoneDateFormatter1.dateFromString("2016-02-05")!
        entity.setValue("3.1", forKey: "distanceOfRun")
        entity.setValue(date, forKey: "dateOfRun")
        do{
            try moc.save()
            print("save was successful")
        }
        catch{

            print("Entry was not saved")        }

        date = myTimeZoneDateFormatter1.dateFromString("2016-02-07")!
        entity.setValue("3", forKey: "distanceOfRun")
        entity.setValue(date, forKey: "dateOfRun")
        do{
            try moc.save()
            print("save was successful")
        }
        catch{

            print("Entry was not saved")        }

任何试图理解这一点的帮助都会让我非常感激。

1 个答案:

答案 0 :(得分:1)

这是因为每次进行save()时都会重新保存相同的对象属性。您应该使用此方法为每个对象创建一个新实体:

let newobject = NSEntityDescription.entityForName("my_entity", inManagedObjectContext: context)
date = myTimeZoneDateFormatter1.dateFromString("2016-02-03")!
newobject.setValue("3.1", forKey: "distanceOfRun")
newobject.setValue(date, forKey: "dateOfRun")

然后再次保存上下文。