Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a new Object into an Entity and set the relationship of that object with an existing object of another entity?

My question can be applied to any type of relationship but in my case I have a one to many.

Let's say I have an Entity Person which has 3 objects:

Brian

Peter

Scott

And each person can have many Jobs. So I have a Job entity that is currently empty. The inverse relationships for both entities are already created and they work great. Just to be clear my problem is not inserting an object(I know how to do that), is the specific way of insertion.

So the more specific question is:

How can I insert one or more job objects into the Job Entity and assign each of them to one of the Person objects that currently exist in Core Data?

like image 415
Fidel Avatar asked Dec 23 '22 22:12

Fidel


1 Answers

After trying a lot of things I finally found a solution. Thanks to Jimmy who game an idea on how to approach this. The key is to realize that you cannot assign a many to one that already exist (Or at least I could not find a way to do it) but you could add many objects to an existing one. In other words you cannot assign an Entity to a Set nor the other way around.

SWIFT 3

So the First Step is to get the one object (in this case the Person) you want to assign many(In this case Jobs) to. This will get you there:

  var person = try MOC.fetch(Person.fetchRequest()).filter { $0.name == "Brian" }

The Second Step is to create a managed object of the Jobs:

 let job = Jobs(context: MOC)
 job.title = "Computers"

And the Third Step is to add the object trough the Person you fetch:

  person[0].addToJobs(job)

If you would like to add more than one Job then you can create a for loop and create as many managed objects you want and add them whenever they are are ready to save. for example:

 for title in jobsTitles {

    let job = Jobs(context: MOC)
    job.title = title

    person[0].addToJobs(job)

 }
like image 168
Fidel Avatar answered Apr 20 '23 00:04

Fidel