已经发布了一个很好的答案,这只是一个建议!
一个好方法是将一个类别添加到 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"];
进一步的优化可能是删除tha实体名称的参数,然后从clazzname中获取名称。这将导致用法:
[ClazzName deleteAllFromEntity];
更干净的隐式(作为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"];