开发者

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

开发者 https://www.devze.com 2022-12-28 23:42 出处:网络
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.Se

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消