iOS 9
迅速
let fetchRequest = NSFetchRequest(entityName: "EntityName") let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do {
try myPersistentStoreCoordinator.executeRequest(deleteRequest, withContext: myContext) } catch let error as NSError {
// TODO: handle the error
}
Objective-C
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"EntityName"];
NSBatchDeleteRequest *deleteRq = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
[myPersistentStoreCoordinator executeRequest:deleteRq withContext:myContext error:&deleteError];
iOS 8 及更早版本
NSFetchRequest *fr = [[NSFetchRequest alloc] init];
[fr setEntity:[NSEntityDescription entityForName:@"EntityName" inManagedObjectContext:myContext]];
[fr setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *objects = [myContext executeFetchRequest:fr error:&error];
//error handling goes here
for (NSManagedObject *object in objects) {
[myContext deleteObject:object];
}
NSError *saveError = nil;
[myContext save:&saveError];
//more error handling here