我试图将一些对象保存到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)")
}
}
请指导我摆脱这个错误。
答案 0 :(得分:3)
当你在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
}