kodeco.com Forums

Updated Course: Beginning Core Data

Learn how to get started with Core Data, including how to model your data, store and fetch objects, filter objects, set up relationships, and more - in this 7-part video course.

This is a companion discussion topic for the original entry at https://www.raywenderlich.com/761-updated-course-beginning-core-data

Hi Luke,

This is a great series, but it doesn’t cover one critical aspect of setting relationships and it doesn’t appear the intermediate course does either. That is, how to set a relationship between two NSManagedObjects at the time of instantiation. For example, if I create a new Object A and one of its properties will be a relationship to Object B, how do I establish that relationship when Object A is initialized? Do you cover this anywhere?


In your scenario, does object B already exist? Is there a reason you can’t set the relationship up on the next line after initialization like:

let a = A(context: managedObjectContext)
a.b = b

try! managedObjectContext.save()

I also assume you could write a custom init method to take in the b object, but that seems like the same thing.

Let me know if I’m missing something!

Hi Luke,

I don’t think you’re missing anything. Yes, object B exists. Every object A will have a relationship to one of the 12 possible Bs. I kept doing research to try and figure it out and here’s what I came up with. I overrode awakeFromInsert on the ‘primary’ object and I’m setting the relationships (weightUnit, lift, and formula) here by getting the managedObjectContext I need from the newly create object.

override func awakeFromInsert() {
    let moc = self.managedObjectContext!
    let defaultUnit = dataManager.fetchDefaultUnit(moc)
    self.weightUnit = defaultUnit
    let defaultLift = dataManager.fetchDefaultLift(moc)
    self.lift = defaultLift
    let defaultFormula = dataManager.fetchDefaultFormula(moc)
    self.formula = defaultFormula
    self.maxAmount = 0.0

Each of those fetch methods uses a value in user defaults to fetch the correct object from the persistent store and returns is to be set as a property of the new object.

What do you think? This is working but Apple docs says I should use primitive accessor methods to set properties if I override this method. Does that apply when the property I’m trying to set is an NSManagedObject?