Petruc
Petruc

Reputation: 23

One-to-Many Relationship in Swift Core Data

I'm building a journal app where you create a FocusArea object, which then contains 30 journal Entry objects.

So I created a one-to-many relationship in my data model.

Then I implemented two NSManagedObject Classes:

@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(Entry) class Entry: NSManagedObject {

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

}

I'm able to add a FocusArea with no problems, but when I try to create 30 Entry objects and store in FocusArea.entries, everything keeps crashing.

What's the correct way to add multiple Entry objects to the FocusArea object?

Am I way off here?

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

Upvotes: 1

Views: 103

Answers (1)

Petruc
Petruc

Reputation: 23

I figured it out. All I had to do was:

newEntry.focus = newFocus.

So instead of setting the relationship between the parent to the child, set it from the child to the parent.

Upvotes: 0

Related Questions