gpt4 book ai didi

ios - 一对多关系核心数据只保存最后一个对象。别人不见了

转载 作者:搜寻专家 更新时间:2023-11-01 06:33:42 24 4
gpt4 key购买 nike

我试图将一些对象保存到 NSSet 但最后一个对象只被保存。我的示例源代码是

func saveData(){
let appDelegate =
UIApplication.shared.delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext

let personEentity = NSEntityDescription.entity(forEntityName: "PersionalDetails",
in:managedContext)
let person = PersionalDetails(entity: personEentity!,
insertInto: managedContext)

let favourateEentity = NSEntityDescription.entity(forEntityName: "Favourites",
in:managedContext)
let favourate = Favourites(entity: favourateEentity!,
insertInto: managedContext)

person.name = "Ragul"
person.age = 28
person.mobileNumber = "0000000000"
person.sex = "male"
for i in 0..<5{
favourate.movie = "Some movie" + "\(i)"
favourate.actor = "Some actor" + "\(i)"
favourate.song = "some song" + "\(i)"
favourate.person = person
}
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
}

请指导我走出这个错误。

最佳答案

当您在 for 循环中设置同一对象的属性时,您只需要最后一个对象,您需要做的是每次在 for 循环的迭代中,您需要创建 Favourites 的新实例> 然后它将存储您创建的所有对象,而不是唯一的最后一个对象。

for i in 0..<5{
let favourate = Favourites(entity: favourateEentity!, insertInto: managedContext)
favourate.movie = "Some movie" + "\(i)"
favourate.actor = "Some actor" + "\(i)"
favourate.song = "some song" + "\(i)"
favourate.person = person
}

关于ios - 一对多关系核心数据只保存最后一个对象。别人不见了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44213656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com