How to implement relationship

Hi,


I'm new in Core data.

What I want to achive is have to entities - Documents and Sales.

Sales should have: price, productname, qty

Documents should have: date, documentkind, number etc.


What I want is create a relationship between them, because every document will have one or more sales, these are going to be the product items.

I know how to achive this when I bind one to one, but when Documents should have more than one Sales....?


Is this the right aproach?

You specify the ordinality of the relationship from source to target, and it can different each way. In other words, "one-to-many" (or "many-to-one") is a possibility for relationships.


So if one document may have more than one sale, that relationship is "to many". If one sale will only refer to one document, that relationship is "to one". And then you likely want to specify that the two relationships are inverses, so that the whole arrangement works right.

Thank yuo fro your prompt replay.

I set one to many, but now I can't figure out how to make the record.

I mean, when create new Sale how to set the value (do I have to) of Sale.document?

If you use the generated header files (like you should), then you set the document value on the Sale object the same way you set any other property. (Or you can use the accessor to add to the to-many relationship, which should be something like addSalesObject. I forget what Swift does for the 'add to to-many relationship set' method...) If you've set Sale.document and Document.sales to inverses, you should only have to set one of the two, and the other will be called for you.

So creating a new sale for an existing document is generally as simple as:

let doc = /* however you get the document reference */
let sale = = NSEntityDescription.insertNewObjectForEntityForName("Sale", inManagedObjectContext: context) as! Sale
sale.document = doc
// then do stuff and call save.


The important thing is to remember to use the right methods to get your objects. The methods that talk about "inserting" an object into a context create a new object. If you're trying to use a previously existing object, you need to use things like fetches or get the object out of a relationship.

How to implement relationship
 
 
Q