Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a one to many relationship in Swift

Tags:

xcode

ios

swift

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

enter image description here

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)

}   
like image 320
KD. Avatar asked Aug 02 '14 04:08

KD.


1 Answers

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.

like image 96
Martin R Avatar answered Oct 29 '22 08:10

Martin R