HelloimDarius
HelloimDarius

Reputation: 695

Core Data Relationship data not being saved

I have two entities. ent1 and ent2 and one to many relationship between them.

let ent1 = NSEntityDescription.insertNewObjectForEntityForName("Ent1", inManagedObjectContext: managedObjectContext) as! Ent1

ent1.a = "aaa"
ent1.b = "bbb"
ent1.ent2?.info = "info"

do{
    try managedObjectContext.save()
} catch let error {
    print("Core Data Error : \(error)")
}

The problem is that only ent1 is being populated and ent2 remains empty.

EDIT:

I tried doing like @Amruta mentioned. And now I'm getting duplicates in my ent2. I would like to have 10 values in ent2, and thousands in ent1. Is that possbile?

Upvotes: 1

Views: 495

Answers (1)

Amruta
Amruta

Reputation: 56

You will first need to insert the ent2 in the same way as ent1

 let ent2 = NSEntityDescription.insertNewObjectForEntityForName("Ent2".....

 ent2.info = "Info"

then,

 ent1.ent2 = ent2

than call the save

Upvotes: 2

Related Questions