Search code examples
ioscore-datadelegationnsfetchedresultscontroller

NSFetchedResultsController delegate not called for API listener


If the code assigns a delegate to the NSFetchedResultsController as follows:

-(id)initWithFetchedResultsController:(NSFetchedResultsController*)fetchedResultsController
{
    self = [super init];
    if (self != nil)
    {
        fetchedResultsController.delegate = self;
        _fetchedResultController = fetchedResultsController;
    }
    return self;
}

The NSFetchedResultsControllerDelegate method – controller:didChangeObject:atIndexPath:forChangeType:newIndexPath: is not ever called on self:

-(void)controller:(NSFetchedResultsController *)controller
  didChangeObject:(id)anObject
      atIndexPath:(NSIndexPath *)indexPath
    forChangeType:(NSFetchedResultsChangeType)type
     newIndexPath:(NSIndexPath *)newIndexPath
{
    NSLog(@"Delegate method called"); // Never called
}

There is no problem with the predicate, a predicate is assigned, and working with notifications directly works.


Solution

  • The problem is that an initial - (BOOL)performFetch:(NSError **)error is never called since this particular code only cares about changes to the result set, not the initial set. However, it would follow that the controller would not notice changes in data it never had. Changing the init method as follows fixes the problem:

    -(id)initWithFetchedResultsController:(NSFetchedResultsController*)fetchedResultsController
    {
        self = [super init];
        if (self != nil)
        {
            fetchedResultsController.delegate = self;
            _fetchedResultController = fetchedResultsController;
            [fetchedResultsController performFetch:nil];
        }
        return self;
    }