meaning-matters meaning-matters - 7 months ago 27
iOS Question

How to delete a selected number of rows from CoreData using NSPredicate?

I want to delete a selected list of items from a CoreData table: A number of Persons with certain

namesToDelete
:

NSError* error = nil;
NSFetchRequest* request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:@"Person"
inManagedObjectContext:managedObjectContext]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"NOT (name IN %@)", namesToDelete];
[request setPredicate:predicate];
NSArray* deleteArray = [managedObjectContext executeFetchRequest:request error:&error];
if (error == nil)
{
for (NSManagedObject* object in deleteArray)
{
[managedObjectContext deleteObject:object];
}

[managedObjectContext save:&error];
//### Error handling.
}
else
{
//### Error handling.
}


This works, but is this the easiest/shortest way to do this in CoreData?

Answer Source

About the best trimming is something like:

NSError*        error        = nil;
NSFetchRequest* request      = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
[request setPredicate:[NSPredicate predicateWithFormat:@"NOT (name IN %@)", namesToDelete]];
NSArray*         deleteArray = [managedObjectContext executeFetchRequest:request error:&error];

if (deleteArray != nil)
{
    for (NSManagedObject* object in deleteArray)
    {
        [managedObjectContext deleteObject:object];
    }

    [managedObjectContext save:&error];
    //### Error handling.
}
else
{
    //### Error handling.
}

Note also that you check if the array is returned as the success criteria, not tat the error in nil. Likewise for the save: you should check the returned BOOL.