How to delete the CoreData Objects with user-defin

2019-09-20 01:25发布

I have object like this

@interface Clubs : NSManagedObject

@property (nonatomic, retain) NSString * catname;
@property (nonatomic, retain) NSString * clubdescription;
@property (nonatomic, retain) NSString * clubid;
@property (nonatomic, retain) NSString * clubname;
@property (nonatomic, retain) NSString * distance;
@property (nonatomic, retain) NSString * logopath;
@property (nonatomic, retain) NSString * phone;
@property (nonatomic, retain) NSString * clubtype;

@end

I want to delete only those object have are particular clubid?

Suppose there are twenty clubs are added to CoreData, only these object I want to delete whose clubid is 120.

Thanks

2条回答
姐就是有狂的资本
2楼-- · 2019-09-20 01:50

There's no batch Core Data method for deleting a set of objects matching a predicate. You will have to retrieve them and delete them by iterating through the results.

NSManagedObjectContext *moc = // get the managed object context
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Clubs"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"clubid == 120"];
NSError *error = nil;
NSArray *entitiesToDelete = [moc executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *entity in entitiesToDelete) {
    [moc deleteObject:entity];
}
[moc save:&error];
if (error) {
    // handle error
}
查看更多
Viruses.
3楼-- · 2019-09-20 01:58
    -(void)deleteClubsEntity:(NSString*)clubId // pass the value 120
    {
        NSError *error = nil;
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest * fetch = [[NSFetchRequest alloc] init];

       [fetch setEntity:[NSEntityDescription entityForName:@"Clubs" inManagedObjectContext: context]];
       [fetch setPredicate:[NSPredicate predicateWithFormat:@"(clubid
 contains[cd] %@)",clubId]];

       NSArray * records = [context executeFetchRequest:fetch error:&error];
           for (NSManagedObject * record in records) {
                [context deleteObject:record];
            }
       [context save:&error];
    }
查看更多
登录 后发表回答