核心数据prepareForDeletion困境

时间:2013-05-14 14:13:29

标签: objective-c cocoa core-data

我对prepareForDeletion的工作原理感兴趣。

我有一个非常简单的对象图。一个名为Individual的班级和一个名为Group的班级。他们之间的关系是多对多的。

到目前为止我所做的是,当我删除一个组时,我会检查属于该组的个人是否只属于被删除的组,如果是,那么我也会删除这些组。

它看起来像这样:

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基本相同的方法。也就是说,当删除Individual时,我会检查即将删除的Individual是否是该组中的最后一个。如果它是最后一个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并在那里尝试删除该组?因为它只有一个人?

要解决此问题,我应该在调用删除后立即调用save,例如:

- (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];
        }
    }
}

0 个答案:

没有答案