Refresh NSFetchedResultsController data?

Daniel picture Daniel · Oct 20, 2011 · Viewed 23.3k times · Source

I can create new managed objects inside my app, in a separate view I have a table view which shows all the objects I have.

When I create a new managed object (in a totally separate view), I am sending out a notification which is trying to get my table view to reload with the new data which includes the new object i just made.

I'm not editing the table view.

There is only one managed context.

I can't grasp what I am doing wrong. If I close the app and relaunch my new object is in the table view. I am trying to call reloadData when I get the notification a new object has been made, and I've also tried performing the fetch again, but all I end up with is an empty table view.

In terms of code, my ListViewController:

@interface MyNotesViewController : UIViewController
{
    NSManagedObjectContext * __managedObjectContext;
    UITableView * _notesTableView;
    MyNotesTableViewDelegate_DataSource * _tableDelegate_DataSource;
}

My viewDidLoad looks like this:

- (void)viewDidLoad
{
    [super viewDidLoad];

    _tableDelegate_DataSource = [[MyNotesTableViewDelegate_DataSource alloc] init];
    _tableDelegate_DataSource.managedObjectContext = __managedObjectContext;
    [_notesTableView setDataSource:_tableDelegate_DataSource];

    NSError * _coreDataError;
    BOOL success = [[_tableDelegate_DataSource fetchedResultsController] performFetch:&_coreDataError];

    if(success){
        [_notesTableView reloadData];
    }
}

In my delegate/datasource object I have:

@interface MyCommutesTableViewDelegate_DataSource : NSObject 

<UITableViewDataSource, NSFetchedResultsControllerDelegate>
{
    NSManagedObjectContext * __managedObjectContext;
    NSFetchedResultsController * __fetchedResultsController;
}

@property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;

@end

Implementation excerpt:

-(NSFetchedResultsController*)fetchedResultsController{
    if(!__fetchedResultsController){
        NSFetchRequest * request = [[NSFetchRequest alloc] init];
        [request setEntity:[NSEntityDescription entityForName:@"Note" inManagedObjectContext:__managedObjectContext]];

        [request setFetchBatchSize:10];

        NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"noteDate" ascending:NO];
        [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
        [sortDescriptor release];

        __fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:__managedObjectContext sectionNameKeyPath:nil cacheName:nil];


        __fetchedResultsController.delegate = self;
        [request release];

    }
    return __fetchedResultsController;
}

I have the stander UITableView data source methods here:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    id <NSFetchedResultsSectionInfo> sectionInfo = 
    [[__fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"NotesTableViewCell";

    NotesTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {        
        NSArray * topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"NotesTableViewCell" owner:nil options:nil];
        for(id currentObject in topLevelObjects){
            if([currentObject isKindOfClass:[UITableViewCell class]]){
                cell = (NotesTableViewCell*) currentObject;
                break;
            }
        }

    }

// Configure the cell.
    Note * _note = [__fetchedResultsController objectAtIndexPath:indexPath];

    [...]

    return cell;
}

UPDATE

I reverted to simply requesting all objects because I had to quick fix my problem, and then I realised, after I save my context, my fetch request I had previously used on the app launch, now returns no data, there's no error but it just returns nothing.

So I guess there's no issue with how I'm implementing NSFetchResultsController. But how could the request start not returning results after I save a new object ?

Note I still get all of my objects if I relaunch, including the newly added one.

standard request:

-(NSArray*)getNotes{
    NSFetchRequest * request = [[NSFetchRequest alloc] init];

    NSEntityDescription * entity = [NSEntityDescription entityForName:@"Note" inManagedObjectContext:[self managedObjectContext]];
    [request setEntity:entity];

    NSSortDescriptor * sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"noteDate" ascending:NO];
    [request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    [sortDescriptor release];

    NSError * coreDataError;
    NSArray * fetchedObjects = [[self managedObjectContext] executeFetchRequest:request error:&coreDataError];
    [request release];

    if(fetchedObjects != nil){
        return fetchedObjects;
    } else {
        NSLog(@"ERR: %@", coreDataError);
        return nil;
    }
}

I am waiting for a notification telling me a new object has been added to Core Data, and then I am calling the above method and then calling reloadData on my tableview...

Answer

huesforalice picture huesforalice · Oct 20, 2011

You are setting your UITableViewController as the NSFetchedResultsControllerDelegate. That's good. Now try to implement the controllerDidChangeContent: method in the TableViewController like so:

- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
   [self.tableView reloadData];
}

Your NSFetchedResultsController will listen to removed or new objects in Core Data and notify its delegate (your TableViewController) of changes. Check the Core Data template project in Xcode to implement this even better with add and removal animations in the UITableView.