开发者

mergeChangesFromContextDidSaveNotification deleting records

开发者 https://www.devze.com 2023-03-17 00:32 出处:网络
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 da

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._persistentStoreCoordin开发者_运维知识库ator;
        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).

0

精彩评论

暂无评论...
验证码 换一张
取 消