我有以下数据模型:
Checklist
@NSManaged var date: NSTimeInterval
@NSManaged var day: Int16
@NSManaged var items: NSSet?
和
ChecklistItem
@NSManaged var completed: Bool
@NSManaged var dayType: Int16
@NSManaged var itemName: String?
@NSManaged var timeOfDay: String?
@NSManaged var checklist: Checklist?
我正在尝试将ChecklistItems数组(NSSet)保存到新的Checklist对象。这是我这样做的代码:
var tasksHolder = [ChecklistItem]()
let moc = CoreDataStack.sharedInstance.managedObjectContext
//puts one day's worth of tasks into the array
for (index, item) in tasks.enumerate() {
let newTask = NSEntityDescription.insertNewObjectForEntityForName(String(ChecklistItem), inManagedObjectContext: moc) as! ChecklistItem
newTask.completed = false
newTask.dayType = DayType.ShakeDay.rawValue
newTask.itemName = item
newTask.timeOfDay = times[index]
do {
try moc.save()
} catch {
print("error")
}
tasksHolder.append(newTask)
}
//do each day
for i in 0..<30 {
let set = NSSet(array: tasksHolder)
let newChecklist = NSEntityDescription.insertNewObjectForEntityForName(String(Checklist), inManagedObjectContext: moc) as! Checklist
newChecklist.date = NSDate().timeIntervalSince1970
newChecklist.day = Int16(i)
newChecklist.items = set
do {
try moc.save()
} catch {
print("error")
}
}
实际的清单对象保存得很好,这是我遇到问题的关系。 ChecklistItem关系仅保存到Checklist的第30个(最后一个)元素。我不确定为什么会这样,但是我假设这与我向Checklist对象添加内容的方式有关。
任何帮助是极大的赞赏。
最佳答案
我不知道这是否是您这里拥有的最佳选择,但是您可以在嵌套的for循环中添加关系,如下所示;
//do each day
for i in 0..<30 {
let newChecklist = NSEntityDescription.insertNewObjectForEntityForName(String(Checklist), inManagedObjectContext: moc) as! Checklist
newChecklist.date = NSDate().timeIntervalSince1970
newChecklist.day = Int16(i)
for i in 0..<taskHolder.count {
let items = newChecklist.mutableSetValueForKey("items")
items.addObject(taskHolder[i])
}
do {
try moc.save()
} catch {
print("error")
}
}
关于ios - Swift Core Data仅将关系保存到循环中的最后一个,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36207806/