如何使用此代码删除之前添加的对象。它是一个收藏夹部分,在开头,我添加了一个灰色的星星,它添加了一个来自fetch的对象。然后它变成黄色,向后的方法应该是黄色的星形=删除。
但我不知道该怎么做。
提前致谢
-(IBAction)inFavoris:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *favorisObj = [NSEntityDescription
insertNewObjectForEntityForName:@"Favoris"
inManagedObjectContext:context];
[favorisObj setValue:idTaxi forKey:@"idTaxi"];
[favorisObj setValue:nomTaxi forKey:@"nomTaxi"];
[favorisObj setValue:taxiCB forKey:@"cb"];
[favorisObj setValue:taxiAvion forKey:@"avion"];
[favorisObj setValue:taxiColis forKey:@"colis"];
[favorisObj setValue:taxiHandicape forKey:@"handicape"];
[favorisObj setValue:taxiHoraires forKey:@"horaire"];
[favorisObj setValue:lugagge forKey:@"lugagge"];
[favorisObj setValue:luxury forKey:@"luxury"];
[favorisObj setValue:languesParlees forKey:@"langues"];
[favorisObj setValue:taxiNote forKey:@"note"];
[favorisObj setValue:taxiPassengers forKey:@"passenger"];
[favorisObj setValue:taxiVote forKey:@"etoiles"];
[favorisObj setValue:taxiTel forKey:@"tel"];
[self.view addSubview:favorisB];
}
更新
我制作了这个方法..它完成了工作:)
-(IBAction)outFavoris:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSString *testEntityId = idTaxi;
NSManagedObjectContext *moc2 = [appDelegate managedObjectContext];
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
fetch.entity = [NSEntityDescription entityForName:@"Favoris" inManagedObjectContext:moc2];
fetch.predicate = [NSPredicate predicateWithFormat:@"idTaxi == %@", testEntityId];
NSArray *array = [moc2 executeFetchRequest:fetch error:nil];
for (NSManagedObject *managedObject in array) {
[moc2 deleteObject:managedObject];
}
[self.view addSubview:favorisO];
}
答案 0 :(得分:62)
非常简单:)
[context deleteObject:favorisObj];
坏的对象全都消失了。
更新
如果你需要一个按钮来删除对象,你可以用这样的东西反转它。
-(IBAction)removeFavoris:(id)sender {
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
[context deleteObject:favorisObj];
}
答案 1 :(得分:25)
删除NSManagedObject后,不要忘记保存Context。所以这是通用代码;
NSManagedObjectContext * context = [self managedObjectContext];
[context deleteObject:objectToDelete];
NSError * error = nil;
if (![context save:&error])
{
NSLog(@"Error ! %@", error);
}
在你的情况下,它应该在for循环之后有片段。
for (NSManagedObject *managedObject in array) {
[moc2 deleteObject:managedObject];
}
NSError * error = nil;
if (![context save:&error])
{
NSLog(@"Error ! %@", error);
}