First Question: Do i also have to enter the instance of the Sales entity into the Sales Entity? or that will be updated automatically since there is a relationship?
Something you might not realize here is that you are inherently saving the object by adding it to the managedObjectContext
. As soon as you do something like
let sale = Sale(context: managedObjectContext)
followed by
managedObjectContext.save()
the context issues a save request to your persistent store (your actual SQL database).
Therefore your question whether you need to store the Sale as well is answered, it will always be stored upon saving the context.
Second Question: If i want to query all the sales that happened to date, do i query the Sales Entity? or do i query the relationship in the Products Entity?
That depends...
First let me give you a little tip/best practise:
Always make sure to set up an inverse relationship
In the Core Data Editor for your Product
entity's relationships you can do something like this:

Your sales relationships look something like this:

A relationship is nothing more but a dependency between two entities, therefore there is always an inverse relationship between two entities, make sure you hook them up as shown above.
Why am I telling you this ? Remember I mentioned it depends what entity you do your query on ? This is where it matters.
For example, if you want the Sale
for a given Product
, you would query the product itself (by querying its relationship called sale
):
let product = [A product instance from your Core Data store]
let sale = product.sale // returns the sale the product is associated to
If you want all the products from a given sale, you would query the Sale
entity leveraging the products
relationship:
let sale = [A sale from your Core Data store]
let products = sale.products // the products contained in the sale
You mentioned that you want all the sales to a given date:
It would not make any sense querying the Product
entity for that because each product only has a relationship to the sale it is contained in.
So, to answer your question, you should query the Sale
entity to retrieve all the sales to a given date.
I hope that helps, let me know if something is unclear.