Tidane Tidane - 1 year ago 157
iOS Question

Delete object in Core Data

How I can delete an object which I had added before with this code. Its a favorites section, in the begin, I add a gray star which adds an object coming from a fetch. Then It turns yellow and the backwards method should be star yellow = deletes.

But I have no idea how to do this.

Thanks in advance

-(IBAction)inFavoris:(id)sender {

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

NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *favorisObj = [NSEntityDescription

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



I made this method.. It gets the job done :)

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


Answer Source

Its quite simple :)

[context deleteObject:favorisObj];

And the bad object is all gone.


You'd just reverse it with something like this if you need a button to delete the object.

-(IBAction)removeFavoris:(id)sender {

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

    NSManagedObjectContext *context = [appDelegate managedObjectContext];

    [context deleteObject:favorisObj];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download