Delete object in Core Data

后端 未结 2 1760
迷失自我
迷失自我 2020-12-29 21:31

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 I

相关标签:
2条回答
  • 2020-12-29 21:51

    Don't forget to save the Context after you have deleted a NSManagedObject. So here is the general code;

    NSManagedObjectContext * context = [self managedObjectContext];
    [context deleteObject:objectToDelete];
    
    NSError * error = nil;
    if (![context save:&error])
    {
        NSLog(@"Error ! %@", error);
    }
    

    In your case it should have the snippet after the for loop.

    for (NSManagedObject *managedObject in array) {
        [moc2 deleteObject:managedObject];
    }
    NSError * error = nil;
    if (![context save:&error])
    {
        NSLog(@"Error ! %@", error);
    }
    
    0 讨论(0)
  • 2020-12-29 22:00

    Its quite simple :)

    [context deleteObject:favorisObj];
    

    And the bad object is all gone.

    Update

    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];
    }
    
    0 讨论(0)
提交回复
热议问题