ios - How can I attach an object with another object in CoreData using a one to many relationship? -


enter image description hereenter image description here

i'm pretty @ working core data when using entities themselves, since i've started playing relationships i've hit few walls can't seem climb on after trying find solution many days. i've got entity called "entityone" -for simplicity reasons- second "entitytwo" entity. entityone has one-to-many relationship entitytwo. i'm trying attach 1 or more entitytwo objects entityone when saving managedobjectcontext, without saving entityone first attaching entitytwo objects after fetching results. how can attach both of them when saving persistent store?

this declaration of both entity descriptions , managedobjects.

let firstentity = nsentitydescription.entityforname("entityone", inmanagedobjectcontext: managedobjectcontext!) let firstitem = nsmanagedobject(entity: firstentity!, insertintomanagedobjectcontext: managedobjectcontext!)  let secondentity = nsentitydescription.entityforname("entitytwo", inmanagedobjectcontext: managedobjectcontext!) let seconditem = nsmanagedobject(entity: secondentity!, insertintomanagedobjectcontext: managedobjectcontext!) 

usually when not working relationships save objects so:

    firstitem.attributeone = titletextfield.text     managedobjectcontext?.save(&error) 

or

firstitem.setvalue("\(titletextfield.text)", forkey: "attributeone" managedobjectcontext?.save(&error) 

so let's on same viewcontroller have data needed create object entityone , 1 or more objects of type entitytwo attach entityone object, how proceed doing so? in advance of help. cheers!

it's easier set relationship "from other direction" since to-one:

seconditem.entityone = firstitem 

but doesn't answer question. to-many relationship represented nsset, use:

firstitem.entitytwo = nsset(object: seconditem) 

or

firstitem.entitytwo = nsset(array: [seconditem, thirditem]) 

which fine if starting no related items, add item existing set:

var myrelateditems : nsmutableset = firstitem.mutablesetvalueforkey("entitytwo") myrelateditems.addobject(seconditem) 

Comments

Popular posts from this blog

dns - How To Use Custom Nameserver On Free Cloudflare? -

python - Pygame screen.blit not working -

c# - Web API response xml language -