Swift核心数据中的一对多关系

时间:2015-09-29 19:09:35

标签: swift core-data nsset

我正在构建一个日记应用,您可以在其中创建一个FocusArea对象,然后该对象包含30个日记条目对象。

所以我在我的数据模型中创建了一对多的关系。

然后我实现了两个NSManagedObject类:

@objc(FocusArea) class FocusArea:NSManagedObject {

@NSManaged var focusName: String
@NSManaged var focusStart: NSDate
@NSManaged var focusEnd: NSDate
@NSManaged var completeFlag: Bool
//@NSManaged var entries: NSSet

var entries: NSMutableOrderedSet {
    return self.mutableOrderedSetValueForKey("entries")
}  

}

@objc(条目) class Entry:NSManagedObject {

 @NSManaged var entryJournal: String
 @NSManaged var entryDate: NSDate
 @NSManaged var completeFlag: Bool
 @NSManaged var entryStatus: Bool
 @NSManaged var focus: FocusArea

}

我能够毫无问题地添加FocusArea,但是当我尝试创建30个Entry对象并存储在FocusArea.entries时,一切都会崩溃。

将多个Entry对象添加到FocusArea对象的正确方法是什么?

我离开这里了吗?

@IBAction func saveFocusArea(sender: AnyObject) {

    if txtFocusName.text != nil {

        let appDel: AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context: NSManagedObjectContext = appDel.managedObjectContext!

        //create new focus area
        let entFocus = NSEntityDescription.entityForName("FocusArea", inManagedObjectContext: context)
        let newFocus = FocusArea(entity:entFocus!, insertIntoManagedObjectContext: context)

        newFocus.focusName = txtFocusName.text!
        newFocus.focusStart = NSDate()
        newFocus.focusEnd = NSDate().dateByAddingTimeInterval(60*60*24*30)
        newFocus.completeFlag = false

        //initialize 30 new entries into core data
        let entEntry = NSEntityDescription.entityForName("Entry", inManagedObjectContext: context)

        for var i = 0; i < 30; i++ {

            let newEntry = Entry(entity:entEntry!, insertIntoManagedObjectContext: context)

            let c = Double(i)
            newEntry.entryDate = NSDate().dateByAddingTimeInterval(60*60*24*c)
            newEntry.entryJournal = ""
            newEntry.entryStatus = false
            newEntry.completeFlag = false

            //THIS IS THE PROBLEM AREA
            newFocus.entries.append(newEntry)
        }
        do {
            try context.save()
        } catch {
            print("There's a problem!")
        }
    }
} 

1 个答案:

答案 0 :(得分:0)

我明白了。我所要做的就是:

newEntry.focus = newFocus。

因此,不是设置父级与子级之间的关系,而是将其从子级设置为父级。