0

My NSFetchedResultsController is not getting updates to newly imported objects.

  1. On a background thread I create a NSManagedObjectContext that is not a child of my main context and add an observer so I can merge the changes.

    NSManagedObjectContext *localContext = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType];
    [localContext setPersistentStoreCoordinator:[[NSManagedObjectContext defaultContext] persistentStoreCoordinator]];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contextDidSave:)
                                                 name:NSManagedObjectContextDidSaveNotification object:nil];
    …
    -(void) contextDidSave:(NSNotification*) notification
    {
        if(![notification.object isEqual:[NSManagedObjectContext MR_defaultContext]] && ![notification.object isEqual:[NSManagedObjectContext MR_rootSavingContext]])
        {
            NSDictionary *userInfo = [notification userInfo];
            NSLog(@"updated: %i, inserted: %i", [userInfo[@"updated"] count], [userInfo[@"inserted"] count]);
            dispatch_async(dispatch_get_main_queue(), ^
                       {
                           [[NSManagedObjectContext MR_defaultContext] mergeChangesFromContextDidSaveNotification:notification];
                       });
        }
    }
    
  2. I create and object and sets its "visible" attribute to NO.
  3. Save the context.
  4. Update the objects "visible" attribute to YES.
  5. Save the context.

    MyEntity *entity = [MyEntity insertInManagedObjectContext:localContext];
    entity.dateCreated = [NSDate date];
    
    if (![localContext save:&error]) {
        NSLog(@"%@", error);
    }
    
    [entity setVisibleValue:YES];
    
    if (![localContext save:&error]) {
        NSLog(@"%@", error);
    }
    

The NSFetchedResultsController has a fetchedRequest that filters on the "visible" attribute.

The updates are being received by contextDidSave:.

Sometimes the objects do make it though and get inserted by the NSFetchedResultsController. This makes me think that I am doing things correctly and I am looking at a CoreData bug. On the other hand I am not sure what exactly is going on in the mergeChangesFromContextDidSaveNotification method.

The code I am used to isolate the problem can be found at https://github.com/onato/CoreDataImportTest

Onato
  • 9,916
  • 5
  • 46
  • 54

0 Answers0