开发者

Replace entities in to-many relationship in Core Data

开发者 https://www.devze.com 2023-03-26 11:56 出处:网络
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 otherwi

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 se开发者_JAVA百科t up with an inverse, cascade delete on the one side, nullify on the many side and the inverse relationship is not optional.


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.


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]
0

精彩评论

暂无评论...
验证码 换一张
取 消