一个很好的答案已经贴出来了,这只是一个推荐!
一个好方法是添加一个类别到NSManagedObject和实现一个方法,就像我做的:
头文件(例如NSManagedObject+Ext.h)
@interface NSManagedObject (Logic)
+ (void) deleteAllFromEntity:(NSString*) entityName;
@end
代码文件:(例如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
... 你唯一要做的就是从应用程序委托获取managedObjectContext,或者你在哪里都有它;)
之后你可以这样使用它:
[NSManagedObject deleteAllFromEntity:@"EntityName"];
进一步的优化可以是删除entityname的参数,而从clazzname获取名称。这将导致使用:
[ClazzName deleteAllFromEntity];
一个更干净的impl(作为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
那时的用法:
[managedObjectContext deleteAllFromEntity:@"EntityName"];