I am new to iOS programming and just need a small help. I am trying to use core data and create a simple insert where there is a one to many relation ship. My very simple core data structure looks like this
Now in the code i have created NSManagedObject subclass as well and am able to create this objects individually. All i need help is how do i create the relationship. My code is is
Xcode generated Father.swift
class Father: NSManagedObject {
@NSManaged var name: String
@NSManaged var fatherToChild: NSSet
}
Xcode generated Child.swift
class Child: NSManagedObject {
@NSManaged var name: String
@NSManaged var child_father: NSManagedObject
}
My Add Data method:
func addData(){
var appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
var context: NSManagedObjectContext = appDel.managedObjectContext!
var fatherEntity = NSEntityDescription.entityForName("Father", inManagedObjectContext: context)
var newFather = Father(entity: fatherEntity, insertIntoManagedObjectContext: context)
newFather.name = "Daddy"
var childEntity = NSEntityDescription.entityForName("Child", inManagedObjectContext: context)
var child1 = Child(entity: childEntity, insertIntoManagedObjectContext: context)
child1.name = "child1"
var child2 = Child(entity: childEntity, insertIntoManagedObjectContext: context)
child2.name = "child2"
//How to map these 2 childs to father? Need help in code here!
context.save(nil)
}
All you have to do is to set the relationship from Child to Father:
child1.child_father = newFather
child2.child_father = newFather
This automatically updates the (inverse) relationship in newFather
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With