Roshan Sah
Roshan Sah

Reputation: 137

CoreData relationship confusion

Suppose I have two entity named Book and Publisher 1. Book has attribute :- writer, title. 2. Publisher has attribute :- name, type I set a relationship :- Publisher to Book ( one to many and set it as inverse relation)

With relationship selected I can see in DataModal inspector a row called Delete Rule with three options 1. Nullify 2. Cascade 3. Deny

What these are and I want to delete Publisher entity only if I delete the last Book

Thank You in advance. I'm just a beginner :)

Upvotes: 0

Views: 54

Answers (1)

RPK
RPK

Reputation: 1994

The docs do a good job explaining these delete rules

https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CoreData/HowManagedObjectsarerelated.html

Relationship Delete Rules

A relationship's delete rule specifies what should happen if an attempt is made to delete the source object. Note the phrasing if an attempt is made. If a relationship's delete rule is set to Deny, it is possible that the source object will not be deleted. Consider again a department's employees relationship, and the effect of the different delete rules.

Deny If there is at least one object at the relationship destination (employees), do not delete the source object (department).

For example, if you want to remove a department, you must ensure that all the employees in that department are first transferred elsewhere (or fired!); otherwise, the department cannot be deleted.

Nullify Remove the relationship between the objects but do not delete either object.

This only makes sense if the department relationship for an employee is optional, or if you ensure that you set a new department for each of the employees before the next save operation.

Cascade Delete the objects at the destination of the relationship when you delete the source.

For example, if you delete a department, fire all the employees in that department at the same time.

No Action Do nothing to the object at the destination of the relationship.

For example, if you delete a department, leave all the employees as they are, even if they still believe they belong to that department.

It should be clear that the first three of these rules are useful in different circumstances. For any given relationship, it is up to you to choose which is most appropriate, depending on the business logic. It is less obvious why the No Action rule might be of use, because if you use it, it is possible to leave the object graph in an inconsistent state (employees having a relationship to a deleted department).

If you use the No Action rule, it is up to you to ensure that the consistency of the object graph is maintained. You are responsible for setting any inverse relationship to a meaningful value. This may be of benefit in a situation where you have a to-many relationship and there may be a large number of objects at the destination.

Upvotes: 1

Related Questions