简体   繁体   中英

mergeChangesFromContextDidSaveNotification deleting records

I am trying to update records in CoreData on a background thread. I am creating NSManagedObjectContext's for each thread per the documentation. I am also registering for notifications for when the data is saved. However, mergeChangesFromContextDidSaveNotification is deleting the entries instead of updating them.

//Notification callback
- (void)_managedObjectContextDidSave:(NSNotification *)notification
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
    });
}

//per thread managed object context
- (NSManagedObjectContext *)managedObjectContext
{
    if ([[[NSThread currentThread] threadDictionary] objectForKey:GVControllerManagedObjectContextKey] == nil) {
        NSPersistentStoreCoordinator *coordinator = self._persistentStoreCoordinator;
        if (coordinator != nil) {
            NSManagedObjectContext *managedObjectContext = [[NSManagedObjectContext alloc] init];
            [managedObjectContext setPersistentStoreCoordinator:coordinator];
            if (![NSThread isMainThread]) {
                [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(_managedObjectContextDidSave:) name:NSManagedObjectContextDidSaveNotification object:managedObjectContext];
            }
            [[[NSThread currentThread] threadDictionary] setObject:managedObjectContext forKey:GVControllerManagedObjectContextKey];
            [managedObjectContext release];
        }
    }

    return [[[NSThread currentThread] threadDictionary] objectForKey:GVControllerManagedObjectContextKey];
}

Looks like I was using a managed object from another thread (added as a property of the objects I was updating).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM