簡體   English   中英

刪除核心數據中的對象

[英]Delete object in Core Data

我如何刪除之前使用此代碼添加的對象。 它是一個收藏夾部分,在開始時,我添加了一個灰色星號,它添加了一個來自獲取的對象。 然后它變成黃色,向后的方法應該是星黃色=刪除。

但我不知道該怎么做。

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

} 

它很簡單:)

[context deleteObject:favorisObj];

壞對象都消失了。

更新

如果你需要一個按鈕來刪除對象,你只需用這樣的東西來反轉它。

-(IBAction)removeFavoris:(id)sender {

    AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];

    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    [context deleteObject:favorisObj];
}

不要忘記在刪除 NSManagedObject 后保存上下文。 所以這是通用代碼;

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM