CoreData delete multiple objects
As I know, there isn't a method for that... You should do like you're already doing. There is a method called deletedObjects
but it just returns the set of objects that will be removed from their persistent store during the next save operation, as described in class reference.
iOS 9 and later
Swift
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 and older
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
iOS10 & Swift 3
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "EntityName")
let deleteRequest = NSBatchDeleteRequest( fetchRequest: fetchRequest)
do{
try mContext.execute(deleteRequest)
}catch let error as NSError {//handle error here }
This deletes all the objects of EntityName
but you can apply additional filtering with NSPredicate