How do you sync a new Core Data entity via data graph with the code?

41 views Asked by At

I merely want to add an entity to an existing NSManagedObject Data Graph and access that entity in code. In this case, I've added 'Address':

enter image description here

The existing code works. I merely added:

let address = Address(context:self.context!)

...as was originally done with the Person() entity.

Here's the error:
enter image description here

Here's the code:

func application(_ application: UIApplication, didFinishLaunchingWithOptions
        launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

        self.context = persistentContainer.viewContext
        let storyboard = self.window?.rootViewController?.storyboard
        guard let vc = storyboard?.instantiateViewController(withIdentifier: "RootViewController") as? RootViewController
            else { fatalError("Cannot instantiate root view controller") }
        vc.context = self.context
        self.window?.rootViewController = vc    // Note: necessary to keep the app del's context instance within vc.

        let address = Address(context:self.context!)

        let person = Person(context: self.context!)
        person.firstName = "Foo"
        person.lastName = "Bar"

        person.cars = NSSet(array: [
            Car(context: self.context!).configured(maker: "VW",
                                                   model: "Sharan",
                                                   owner: person),
            Car(context: self.context!).configured(maker: "VW",
                                                   model: "Tiguan",
                                                   owner: person)
            ])

        do{
            try saveContext()
        } catch {
            //something bad happened, handle this situation appropriately
        }

        return true
    }

Question: How do I make the code see the new entity 'Address'?

0

There are 0 answers