E-Madd
E-Madd

Reputation: 4572

How to delete all objects for a given entity from the ManagedObjectContext

I don't want to use the reset method for my ManagedObjectContext. I only need to remove all of the objects for a specific entity, but I don't see any methods for doing this. Selecting all of the objects for a specific entity and looping over each and deleting them works, but it's very slow.

Upvotes: 3

Views: 604

Answers (2)

DrFloyd5
DrFloyd5

Reputation: 13787

Categories to the rescue! 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

Usage

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

Categories are awesome.

Upvotes: 0

Alex Reynolds
Alex Reynolds

Reputation: 96927

Selecting all of the objects for a specific entity and looping over each and deleting them works

That's pretty much how you do it.

Upvotes: 7

Related Questions