Reputation: 9902
I know both Apple and the consensus say that in Core Data, every relationship should have an inverse. This is not a question asking whether that is indeed the case. I do believe Apple and the experts. I'd just like to understand the reasoning. Unfortunately, reasons are often not given.
Sometimes, it is impractical to have inverse relationships. Sometimes, I would like to forego them. But I'd like to know what the tradeoffs are (instead of an ominous "don't do that, it's dangerous").
So, I am asking what are the reasons not to forego the inverse relationship in Core Data?
Upvotes: 1
Views: 209
Reputation: 70966
The usual answer is something like "they're required to help maintain data integrity". Here's a specific example.
Suppose you have a Department
entity and an Employee
entity. Department
has a to-many relationship employees
to Employee
but there is no corresponding inverse relationship. A bit contrived, since there are probably good reasons to want to easily look up an employee's department, but I wanted a simple example.
Now, suppose I have a specific Department instance named "Department X", which is for all the company's spies. Department X has 7 employees. But then, calamity! Agent 004 is killed by a rival company. So your app deletes Agent 004's Employee
instance.
Now, how many employees does the Department
instance for Department X have?
If you haven't been careful about what you're doing, it still has seven employees. But one of them doesn't have any data. Why? Because nobody told the Department
instance that one of its employees had gone away, so it thinks nothing has changed. Six regular employees and, I guess, one undead zombie employee.
To keep things clean, you also need to get the Department
instance for Department X and remove Agent 004's entry from its list of employees.
If there had been an inverse relationship from Employee
back to Department
, and you used sane deletion rules, this would have happened automatically. When you deleted Agent 004's instance, Department X's employee list would immediately show only six employees.
It's not impossible to get this right without an inverse relationship, but if you do have one, Core Data will look after certain details that help maintain your object graph integrity.
Upvotes: 5