Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Core Data: DELETE WHERE

I know how to use NSPredicate to perform a SQL SELECT-like operation. How can I perform something like DELETE WHERE? Do I have to call [NSManagedObjectContext deleteObject] for each fetched object? Thanks

NSError *error;

NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:TASK_ENTITY inManagedObjectContext:managedObjectContext]];

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"label LIKE  %@", label];
[request setPredicate:predicate];

NSArray *array = [managedObjectContext executeFetchRequest:request error:&error];

[managedObjectContext deleteObject:[array objectAtIndex:0]];
like image 472
pistacchio Avatar asked Nov 16 '11 20:11

pistacchio


People also ask

How do you delete Core Data records?

Deleting a record from a persistent store involves three steps: fetch the record that needs to be deleted. mark the record for deletion. save the changes.

Where does Core Data store data?

The persistent store should be located in the AppData > Library > Application Support directory. In this example you should see a SQLite database with extension . sqlite. It is possible that you don't see the persistent store in the Application Support directory.

How do I delete Core Data in swift 4?

Table views have a built-in swipe to delete mechanic that we can draw upon to let users delete commits in our app. Helpfully, managed object context has a matching delete() method that will delete any object regardless of its type or location in the object graph.

What is delete rule in Core Data?

A delete rule defines what happens when the record that owns the relationship is deleted. Select the notes relationship of the Category entity and open the Data Model Inspector on the right. By default, the delete rule of a relationship is set to nullify. Core Data supports four delete rules: No Action.


1 Answers

I believe looping over the returned array and calling [NSManagedObjectContext deleteObject:] is the "correct"/idiomatic way to do it. It might seem inefficient, but remember that the fetch command doesn't actually fetch the objects' data, and the deleteObject: method just marks the object for deletion, which gets applied when you send [NSManagedObjectContext save:]. Not knowing the internals of Core Data I can't tell you whether it's as efficient as a DELETE WHERE query (presumably Core Data has the indexed primary keys in memory from the fetch, and uses those) but in my experience with profiling Core Data apps it's not significantly slower than saving new or updated objects.

like image 105
Alex Michaud Avatar answered Nov 11 '22 14:11

Alex Michaud