Delete an object in core data

后端 未结 3 1683
清歌不尽
清歌不尽 2021-02-06 00:26

I have an entity in my core data model like this:

@interface Selection : NSManagedObject

@property (nonatomic, retain) NSString * book_id;
@property (nonatomic,         


        
相关标签:
3条回答
  • 2021-02-06 00:50

    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();
    }
    
    0 讨论(0)
  • 2021-02-06 00:53

    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.

    0 讨论(0)
  • 2021-02-06 00:54

    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.

    0 讨论(0)
提交回复
热议问题