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]];
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.
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.
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.
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.
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.
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