Swift Core Data仅保存与循环中最后一个的关系

时间:2016-03-24 18:46:47

标签: ios swift core-data xcode7 relationships

我有以下数据模型:

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")
        }
    }

实际的Checklist对象保存完好,这是我遇到问题的关系。 ChecklistItem关系仅保存到核对表的第30个(最后一个)元素。我不确定为什么会发生这种情况,但我认为它与我向Checklist对象添加内容的方式有关。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

我不知道这是否是您在此处所拥有的最佳选择,但您可以在嵌套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")
    }
}