Removing a specific entry/row from Core-Data
As @Nektarios said, you are dealing with objects here so you want to find an object that has a particular attribute value. You that with a fetch request and a predicate.
NSNumber *soughtPid=[NSNumber numberWithInt:53]; NSEntityDescription *productEntity=[NSEntityDescription entityForName:@"Product" inManagedObjectContext:context]; NSFetchRequest *fetch=[[NSFetchRequest alloc] init]; [fetch setEntity:productEntity]; NSPredicate *p=[NSPredicate predicateWithFormat:@"pid == %@", soughtPid]; [fetch setPredicate:p]; //... add sorts if you want them NSError *fetchError; NSArray *fetchedProducts=[self.moc executeFetchRequest:fetch error:&fetchError]; // handle error
The fetchedProducts
array will contain all the objects of the entity Product
whose pid
attribute equals soughtPid
. Note that the predicate fulfills the same function logically as the where
clause in SQL.
Once you have the objects you just tell the context to delete them:
for (NSManagedObject *product in fetchedProducts) { [context deleteObject:product]; }
When you next save the context, the object's data will be deleted from the persistent store file.
Like Sqlite's "DELETE from tableName WHERE condition", you have no single step to delete MULTIPLE
objects from CoreData.
In CoreData, first you have to fetch objects that has to be deleted, using NSFetchRequest
and NSPredicate
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"EntityName"];NSPredicate *predicate = [NSPredicate predicateWithFormat:@"propertyName == %@", value];[request setPredicate:predicate];NSError *error = nil;NSManagedObjectContext *managedObjectContext;//Get your ManagedObjectContext;NSArray *result = [managedObjectContext executeFetchRequest:request error:&error];
Then, you should iterate through every NSManagedObject
and call deleteObject:
from your NSManagedObjectContext
.
if (!error && result.count > 0) { for(NSManagedObject *managedObject in result){ [managedObjectContext deleteObject:managedObject]; } //Save context to write to store [managedObjectContext save:nil];}
Remember to think of Core Data as a graph and not a DB, so the concept of rows doesn't apply. Instead, you want to remove a specific object from the graph.
You used insertNewObjectForEntityForName:inManagedObjectContext:
to insert it. Use deleteObject:
to delete it, such as:
[aContext deleteObject:aManagedObject];
In your case,
[context deleteObject:Product];
Good luck
See Apple's explanation here
Note: when you delete, depending on your scheme, that can have different implications. For example it could delete everything further down the child-path of your Core Data object graph. Make sure you think hard when designing your schema about how that should work. If you set it up right, this can be a huge advantage to you.