我对 prepareForDeletion 的工作原理很感兴趣。
我有一个非常简单的对象图。一类叫Individual
,一类叫Group
。它们之间的关系是多对多的。
到目前为止我所做的是,当我删除一个组时,我检查属于该组的个人是否只属于被删除的组,如果是,那么我也删除这些个人。
它看起来像这样:
组.m
- (void)prepareForDeletion {
//individual check: if this group was the last associated with that individual, delete the individual
for (Individual *individual in self.individuals) {
if ([individual.groups count] == 1) {
[self.managedObjectContext deleteObject:individual];
}
}
}
现在我有了对Individual
. 也就是说,当 anIndividual
被删除时,我检查Individual
即将被删除的是否是组中的最后一个。如果是最后一个Individual
,则也应删除该组。
个人.m
- (void)prepareForDeletion {
// Group check: if this individual was the last associated with that group, delete group
for (Group *group in self.groups) {
if ([group.individuals count] == 1) {
[self.managedObjectContext deleteObject:group];
}
}
}
因此,如果我选择删除与一个组只有一种关系的个人的路线。然后应该删除个人和组:
Individual *individualToDelete = ...
[moc deleteObject:individualToDelete];
现在在 Individual.m 中的 prepareForDeletion 中,它将删除该组(因为它只有一个人)但是现在它将进入 Group.m 中的 prepareForDeletion 并且它也会尝试删除该组?因为它只有一个人?
为了解决这个问题,我应该在调用删除后立即调用保存,例如:
- (void)prepareForDeletion {
// Group check: if this individual was the last associated with that group, delete group
for (Group *group in self.groups) {
if ([group.individuals count] == 1) {
[self.managedObjectContext deleteObject:group];
[self.managedObjectContext save:nil];
}
}
}