I know how to delete a single object in CoreData I'm just wondering if theres a simpler way of deleting multiple objects?
For single delete you can use
[moc deleteObject:someManagedObject];
but there is no equivalent for multiple objects.
At the moment I'm thinking of doing...
NSArray *arrayOfManagedObjectsToDelete = //...
for (SomeManagedObjectClass *managedObject in arrayOfManagedObjectsToDelete) {
[moc deleteObject:managedObject];
}
but I wasn't sure if there was another way of doing this?
ideally a method like...
- (void)deleteObjects:(NSSet*)objects
on NSManagedObjectContext
or some similar method.
iOS 9
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With