A good answer was already posted, this is only a recommendation!
A good way would be to just add a category to NSManagedObject and implement a method like I did:
Header File (e.g. NSManagedObject+Ext.h)
@interface NSManagedObject (Logic) + (void) deleteAllFromEntity:(NSString*) entityName; @end
Code File: (e.g. NSManagedObject+Ext.m)
@implementation NSManagedObject (Logic) + (void) deleteAllFromEntity:(NSString *)entityName { NSManagedObjectContext *managedObjectContext = [AppDelegate managedObjectContext]; NSFetchRequest * allRecords = [[NSFetchRequest alloc] init]; [allRecords setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:managedObjectContext]]; [allRecords setIncludesPropertyValues:NO]; NSError * error = nil; NSArray * result = [managedObjectContext executeFetchRequest:allRecords error:&error]; for (NSManagedObject * profile in result) { [managedObjectContext deleteObject:profile]; } NSError *saveError = nil; [managedObjectContext save:&saveError]; } @end
... the only thing you have to is to get the managedObjectContext from the app delegate, or where every you have it in ;)
afterwards you can use it like:
[NSManagedObject deleteAllFromEntity:@"EntityName"];
one further optimization could be that you remove the parameter for tha entityname and get the name instead from the clazzname. this would lead to the usage:
[ClazzName deleteAllFromEntity];
a more clean impl (as category to NSManagedObjectContext):
@implementation NSManagedObjectContext (Logic) - (void) deleteAllFromEntity:(NSString *)entityName { NSFetchRequest * allRecords = [[NSFetchRequest alloc] init]; [allRecords setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self]]; [allRecords setIncludesPropertyValues:NO]; NSError * error = nil; NSArray * result = [self executeFetchRequest:allRecords error:&error]; for (NSManagedObject * profile in result) { [self deleteObject:profile]; } NSError *saveError = nil; [self save:&saveError]; } @end
The usage then:
[managedObjectContext deleteAllFromEntity:@"EntityName"];