一对多关系核心数据只保存最后一个对象。其他人不见了
Posted
技术标签:
【中文标题】一对多关系核心数据只保存最后一个对象。其他人不见了【英文标题】:One-To-Many relationship core data saves only last object. Others are missing 【发布时间】:2017-05-27 06:21:23 【问题描述】:我正在尝试将一些对象保存到 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)")
请指导我摆脱这个错误。
【问题讨论】:
【参考方案1】:当您在 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
【讨论】:
@Ragul 欢迎朋友 :)以上是关于一对多关系核心数据只保存最后一个对象。其他人不见了的主要内容,如果未能解决你的问题,请参考以下文章
获取一对多的核心数据关系第一次返回正确的对象,但其他时候返回空集