从目标c中的核心数据中删除特定实体的特定数据?
问题描述:
我的核心数据中有两个实体名为“History”和“Favorite”。我想从“历史”实体中删除一些特定的数据,如“达卡”。如何删除这个。提前致谢。从目标c中的核心数据中删除特定实体的特定数据?
答
希望它能帮助你。
NSString* aType = @"History";
NSString *tp = @"Dhaka";
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:aType inManagedObjectContext:self.managedObjectContext]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:@"(type == %@)",tp ]; //where type is the attribute
[request setPredicate:predicate];
NSArray* ar = [self.managedObjectContext executeFetchRequest:request error:nil];
NSLog(@"@@@@@@@@@@@@@ Data from DB : %@",ar);
for(id anObj in ar){
[managedObjectContext deleteObject:anObj];
}
[self.managedObjectContext save:nil];
predicate=nil;
答
试试这个:
objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [objAppDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"History"];
NSArray *recordArray =[[NSArray alloc]initWithArray:[context executeFetchRequest:request error:nil]];
objDataClass = [recordArray objectAtIndex:0]; // here objDataClass is a instance of DataClass derived from NSObject which define column name
[context deleteObject:objDataClass]; // Delete particular data with index
if ([context hasChanges])
{
[context save:nil];
}
else
{
NSLog(@"Object Deleted.....");
}
希望它会帮助你。 :)