如何用用户定义的ID删除CoreData对象?

我有这样的对象

@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 

我想只删除那些对象有特定的clubid?

假设有二十个俱乐部被添加到CoreData,只有这些对象我想删除其clubid为120。

谢谢

  -(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]; } 

没有用于删除与谓词匹配的一组对象的批处理核心数据方法。 您将不得不通过遍历结果来检索它们并删除它们。

 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 }