2012-06-14 178 views
26

如何刪除我之前使用此代碼添加的對象。它是一個最喜歡的部分,在開始時,我添加了一個灰色的星星,它添加了一個來自獲取的對象。然後它變成黃色,向後的方法應該是星形黃色=刪除。刪除核心數據中的對象

但我不知道如何做到這一點。提前

感謝

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

你必須拯救managedObject終於做出改變成coredata –

回答

60

它很簡單:)

[context deleteObject:favorisObj]; 
工作

不好的東西都不見了。

更新

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

-(IBAction)removeFavoris:(id)sender { 

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

    NSManagedObjectContext *context = [appDelegate managedObjectContext]; 

    [context deleteObject:favorisObj]; 
} 
+0

好吧,但我怎麼能做出這與上述相反的方法? – Tidane

+0

我必須像上面那樣聲明favorisObj?它仍然不會刪除任何東西:( – Tidane

+0

)上面你正在創建favorisObj然後添加東西,你需要把同一個對象作爲參數傳遞給'[context deleteObject:arg]' –

24

不要忘記在刪除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); 
} 
相關問題