How to remove all objects for a given object from ManagedObjectContext

I do not want to use the reset method for my ManagedObjectContext. I only need to delete all objects for a specific object, but I do not see any methods for this. The selection of all objects for a particular object and their cyclic movement, as well as their removal, but very slowly.

+3
source share
2 answers

The selection of all objects for a particular object and their cyclic movement and removal of their work

This is pretty much how you do it.

+7
source

Categories for help! Yet again.

NSManagedObjectContext + MyExtensions.h

@interface NSManagedObjectContext (MyExtensions)

-(void) deleteAllInstancesOfEntity:(NSString*) entity;

@end

NSManagedObjectContext + MyExtensions.m

#import "NSManagedObjectContext+MyExtensions.h"


@implementation NSManagedObjectContext (MyExtensions)

-(void) deleteAllInstancesOfEntity:(NSString*) entity {
     NSError* error;

     for (NSManagedObject* o in
            [self executeFetchRequest:[NSFetchRequest fetchRequestWithEntityName:entity]
                                error:&error]) {
          [o.managedObjectContext deleteObject:o];
     }
}

@end

NSManagedObjectContext *myMOC = ...;
[myMOC deleteAllInstancesOfEntity:@"SmellyCheese"];

.

0

Source: https://habr.com/ru/post/1743567/


All Articles