Delete an object in core data

醉酒当歌 提交于 2019-12-03 03:42:56

What Mike Weller wrote is right. I'll expand the answer a little bit.

First you need to create a NSFetchRequest like the following:

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];    
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Selection" inManagedObjectContext:context]];

Then you have to set the predicate for that request like the following:

[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"content == %@ AND page_id == %@ AND book_id == %@", contentVal, pageVal, bookVal]];

where

NSString* contentVal = @"test";
NSNumber* pageVal = [NSNumber numberWithInt:5];
NSString* bookVal = @"1331313";

I'm using %@ since I'm supposing you are using objects and not scalar values.

Now you perform a fetch in the context with the previous request:

NSError* error = nil;
NSArray* results = [context executeFetchRequest:fetchRequest error:&error];

results contains all the managed objects that match that predicate.

Finally you could grab the objects and call a deletion on them.

[context deleteObject:currentObj];

Once done you need to save the context as per the documentation.

Just as a new object is not saved to the store until the context is saved, a deleted object is not removed from the store until the context is saved.

Hence

NSError* error = nil;
[context save:&error];

Note that save method returns a bool value. So you can use an approach like the following or display an alert to the user. Source NSManagedObjectContext save error.

NSError *error = nil;
if ([context save:&error] == NO) {
    NSAssert(NO, @"Save should not fail\n%@", [error localizedDescription]);
    abort();
}

You should perform a fetch request using an NSPredicate with the appropriate conditions, and then call the deleteObject: method on NSManagedObjectContext with each object in the result set.

In addition to Mike Weller and flexaddicted, after calling [context deleteObject:currentObj]; you need to save: context:

NSError *error = nil;
[context save:&error];

As from documentation:

Just as a new object is not saved to the store until the context is saved, a deleted object is not removed from the store until the context is saved.

That made matter in my case.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!