3
votes

When I retrieve an entity from the one side of a one-to many relationship, I create a mutable array from the set that is the collection of entities from the relationship. I manipulate, edit or otherwise change those entities, possibly delete existing or add new. When through with the changes I simply use the array to create a new set then replace the original set with that which I created like so:

self.myOneSideEntity.theManySideEntitiesRelationship = [NSSet setWithArray:myNewArrayOfEntities];

It occurred to me that replacing the set may not be deleting the old members. What happened to them? Is this the proper way to edit the collection of related objects? Am I leaving any kind of orphans or going against best practices with this technique?

My relationship is set up with an inverse, cascade delete on the one side, nullify on the many side and the inverse relationship is not optional.

2

2 Answers

6
votes

I've spent some days to understand similar behavior in my application.

Relation's "Delete Rule" works only when the object that contains relation is deleted itself. If you simply replace one set of objects with another (as you do) - nothing happens. Child objects that were in old set will simply have inverse relations set to nil. So if that relation (from child side) is not optional, you will get CoreData error when saving context.

For now I didn't find any way to manage this, except manual deletion of old objects.

0
votes

For me the issue was with getting objects which were wired with current object. (groupObject.docs) It was solved when I add context by which I get this data. I'm using MagicalRecord:

[GroupObject MR_findAllInContext:[NSManagedObjectContext MR_defaultContext]]

instead of

[GroupObject MR_findAll]