Removing a specific entry/row from Core-Data

John S picture John S · Jun 29, 2011 · Viewed 31.7k times · Source

I'm using core data in my app, and i'm confused when it comes to removing certain rows or entries from the core data storage. I insert some products in to the storage like so:

NSManagedObject *Product = [NSEntityDescription insertNewObjectForEntityForName:@"Product" inManagedObjectContext:context];
[Product setValue:[NSNumber numberWithFloat:id] forKey:@"pid"];
[Product setValue:[NSNumber numberWithFloat:quantity] forKey:@"pquantity"];

This works fine for insertion. However, later in the app, I want to remove the entry where for example, the pid is 53. How would I go about removing only this row/entry? The equivalent SQL would be something like:

DELETE from Product WHERE pid = '53'

I would greatly appreciate some example code, as I can't seem to figure this one out.

Thanks for any help.

Answer

TechZen picture TechZen · Jun 29, 2011

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.