Trying to implement master-child Managed Object Context when doing mass delete in Core Data

女生的网名这么多〃 提交于 2019-12-06 15:36:53

I think it not require two MOC, you are able to solve it by one. Just pass it as a parameter to the fetchOtherMOByMyMo:(MyMo *)mo onContext:(NSManagedObjectContext *)context.

And you forget to use performBlock: Check, it should work without crashing:

- (void)massDelete {

...
__weak typeof(self) weakSelf = self;
self.managedObjectContext performBlock:^{
       NSArray *objectsToPurge = [weakself.managedObjectContext executeFetchRequest:fetchRequest error:&error];

       if (objectsToPurge) {

            [objectsToPurge enumerateObjectsUsingBlock:^(MyMO *mo, NSUInteger idx, BOOL *stop) {

                OtherMO *otherMO = [weakself fetchOtherMO:mo onContext:weakself.managedObjectContext];

                if (otherMO) {
                    [weakself.managedObjectContext deleteObject:otherMO];
                }

                [weakself.managedObjectContext deleteObject:mo];

            }];
        }

        [weakself.managedObjectContext save:&purgeError];
});
}

- (OtherMO *)fetchOtherMO:(MyMO *)mo onContext:(NSManagedObjectContext *)context{
        NSError *error;

        // Create fetch request
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"OtherMO" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];

        // Create predicate
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"myMO == %@", mo];
        [fetchRequest setPredicate:pred];

        NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
        if ([items count]>0) {
            return [items firstObject];
        } else {
            return nil;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!