Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData delete multiple objects

Tags:

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.

like image 384
Fogmeister Avatar asked Jan 28 '13 11:01

Fogmeister


3 Answers

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
like image 98
ZaEeM ZaFaR Avatar answered Sep 17 '22 17:09

ZaEeM ZaFaR


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

like image 35
Chris Balavessov Avatar answered Sep 20 '22 17:09

Chris Balavessov


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.

like image 35
CainaSouza Avatar answered Sep 18 '22 17:09

CainaSouza