Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: avoiding retain cycles in to-many relationships

I'm still learning my way through iOS development and working with Core Data and have just come across retain cycles.

It is my understanding from reading the Core Data Programming Guide that after you're done working with a relationship, you use the managed object context method refreshObject:mergeChanges to ensure that the retain cycle is broken.

So lets say I have a to-many relationship between a Department and its Employees, and in my code I access the employees relationship from department, does that mean I'll now need to loop through each employee object and call refreshObject:mergeChanges method? In code this would be

for (Employee *anEmployee in department.employees) {
  //some code that accesses an employee's properties

  [context refreshObject:enEmployee mergeChanges:NO];
}

It seems that if I don't do that, each employee object I access will now contain a reference to the department and I will end up with retain cycles.

Is my understanding correct here? Is this a standard approach when dealing with to-many relationships in Core Data? Thanks.

like image 786
Bart Jedrocha Avatar asked Oct 21 '10 04:10

Bart Jedrocha


People also ask

What is relationship in core data?

Inverse relationships enable Core Data to propagate change in both directions when an instance of either the source or destination type changes. Every relationship must have an inverse. When creating relationships in the Graph editor, you add inverse relationships between entities in a single step.

What is a retain cycle?

Retain Cycle is the condition When 2 objects keep a reference to each other and are retained, it creates a retain cycle since both objects try to retain each other, making it impossible to release. Here The "Grandparent" retains the "parent" and "parent" retains the "child" where as "child" retains the "parent"..


1 Answers

As you can check at Breaking Relationship Retain Cycles, the retain cycles are necessary to prevent deallocation of unwanted objects. It means that you keep the the object retained while you are using it.

The refreshObject:mergeChanges should be used if you are done with that object and you want to turn it into fault, to dispose memory if possible. It won't necessarily release the object in the other end of the relationship, it will only set a flag to core data that the object can be turned into fault if necessary.

like image 137
vfn Avatar answered Oct 02 '22 15:10

vfn