Add child object in Core Data relationship - Swift4

Viewed 785

I have two Entitys one called Cupboard one Drawer with a one to many Relationship Cupboard<->>Drawer. For Cupboards I use a collectionView and I created a segue to a tableView(Drawer). But I don't know how I add new Drawers to Cupboard when I'm in the DrawerViewController

I save my Cupboard like this:

func saveCupboard(name: String, type: String){
    let cupboard = NSEntityDescription.insertNewObject(forEntityName: "Cupboard", into: managedContext) as! Cupboard

    cupboard.name = name
    cupboard.type = type

    saveContext()

}

lazy var managedContext: NSManagedObjectContext = {

    var context = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)

    context.persistentStoreCoordinator = self.storeCoordinator

    return context
}()

func saveContext() {
    if managedContext.hasChanges {
        do {
            try managedContext.save()
        } catch {
            print(error.localizedDescription)
        }
    }
}

My segue:

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "showDrawer" {
        let dst = segue.destination as! DrawerViewController

        guard let indexPath = collectionView.indexPathsForSelectedItems else{
            return
        }
        dst.cupboard = ??
    }
}

Maybe someone can help me there. Thank you in advance

Edit:

 lazy var fetchedResultsCtrl: NSFetchedResultsController<Cupboard> = {
    let request: NSFetchRequest<Cupboard> = Cupboard.fetchRequest()

    let sort = NSSortDescriptor(key: "name", ascending: true)

    request.sortDescriptors = [sort]

    let fetchedCtrl = NSFetchedResultsController(fetchRequest: request, managedObjectContext: appDelegate.coreDataResource.managedContext, sectionNameKeyPath: nil, cacheName: nil)

    fetchedCtrl.delegate = self

    return fetchedCtrl
}()
2 Answers
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    if segue.identifier == "showDrawer" {
        let dst = segue.destination as! DrawerViewController

        guard let indexPath = collectionView.indexPathsForSelectedItems else{
            return
        }
        dst.cupboard = cupboards[indexPath.row] as! Cupboard //Pass the cupboard to DrawerViewController.
    }
}

You can pass the cupboard to DrawerViewController like above. Then at the time of adding new drawer in DrawerViewController, you have to just set

let newDrawer = Drawer(context:moc) 
newDrawer.cupboard = cupboard

As there is one to many relationships between cupboard and drawer.

But I don't know how I add new Drawers to Cupboard when I'm in the DrawerViewController

Make sure that you have enabled class generation for your managed object model. Then you have classes Drawer and Cupboard. So you would say:

let drawer = Drawer(context:context)
drawer.cupboard = // ... the cupboard we already saved  
Related