Reputation: 582
My model have 2 Entity (Category and News) with many to many relationship: (It mean a category may have many news and a news article may belong to one or more Category).
Below is my design:
Category (attributes: categoryID, title, show, position) and a relationship with News Entity called "news".
"news" relationship has destination is "News", inverse relationship is "categories", type to-many relationship and delete rule is cascade.
News (attributes: newsID, quote, content, link) and a relationship with Category Entity called "categories".
"categories" Relationship has destination is "Category", inverse relationship is "news", type to-many relationship and delete rule is nullify.
Object graph look like this:
News <<-------------->> Category
My question is:
1> Is my designed model is good ?
2> Arcoding to my designed model, if I delete a News object from it context example like:
id newsObjectToDelete = .... [managedObjectContext deleteObject:newsObjectToDelete];
Does Category object that newsObjectToDelete belong to automatically remove newsObjectToDelete from NSSet of relationship "News".
3> If I want to constraints that a "News" must belong to at least one "Category". How to implement that constraints
Thank in advance. Sorry for poor English
Upvotes: 1
Views: 524
Reputation: 981
It's tough to say whether or not this is a good fit for your app, but it looks like a pretty standard relationship.
If you delete an object, it is automatically removed from all Core Data relationships. Don't worry about a dangling reference to some deleted object, Core Data handles that for you.
Core Data can really only generate an error (and blocking the save) or take some automatic action during the save. You can do either of the following:
In Your Data Model: Using the data model editor, uncheck "Optional" for this relationship, and/or set the "Minimum" count to 1:
In Your "News" Subclass: If you need more fine-grained control and/or error reporting, you can check this during validation (to generate an error) or maybe take some automatic actions during the save process.
Note that using validation (either in the model or in your code) is only going to help during the development and debugging processes - calling -save:
on the managed object context will fail, returning NO
and generating an error. This should be a last resort, and really just there to keep bad data from getting into your persistent store. A validation failure like this tells you that some other part of your code is wrong and generating bad objects.
Upvotes: 1