Managed object not deleted properly in my core database

一曲冷凌霜 提交于 2020-01-05 18:04:19

问题


I am trying to delete some objects from my Entity Reservation. I am doing it like this.

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

After that I delete my object I fetch the whole entity again. I can see that the object is delete from my entity. But when I restart my app, all my objects that I deleted in the previous session are back stored in my entity.

I'm using restkit to store my objects that I got back from a webservice. Also when I delete the object, I delete it also in my database.

When I restart my app and look at my logs I see that I don't get the object back from my webservice that I deleted in the previous session, so that's oké. The only problem is that they are somehow stored back in my core database.


回答1:


I am not entirely sure how reskit handles saving/deleting on threads but basically when you setup your NSManagedObjectContext on the main thread you register for notifications.

-(NSManagedObjectContext *)aContext
{
   if (!_aContext) {
       _aContext = [(AppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(mergeChanges:) name:NSManagedObjectContextDidSaveNotification object:nil];
   }
   return _aContext;
}

If a change to context happens on a background thread then a notification will be sent.

-(void)mergeChanges:(NSNotification *)aNotification
{
 // Merge the changes from the notification
 // on the main thread as this is the main
 // context for our application.
 dispatch_async(dispatch_get_main_queue(), ^{

    [self.aContext mergeChangesFromContextDidSaveNotification:aNotification];
 });
}


来源:https://stackoverflow.com/questions/18202241/managed-object-not-deleted-properly-in-my-core-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!