Managed object not deleted properly in my core dat

2019-08-01 06:59发布

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条回答
时光不老,我们不散
2楼-- · 2019-08-01 07:23

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];
 });
}
查看更多
登录 后发表回答