How to delete all objects for a given entity from the ManagedObjectContext
I don't want开发者_StackOverflow社区 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.
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.
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.
精彩评论