Search code examples
ioscore-dataicloud

Refresh UITableView with iCloud changes


I have an app where I have intergrated core data with iCloud. I have the following notifications in my view controller.

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreCoordinatorStoresDidChangeNotification object:coreDataController.psc];

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadFetchedResults:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:coreDataController.psc];

The view controller contains a UITableView that is loaded with core data using NSFetchedResultsController. I am unsure what to put in the following method (called by the notifications above) to refresh the table. I have tried reloading the table, and refetching the data but to no avail. I know that the iCloud is doing its job because if I completely reload the viewcontroller the changed data shows.

- (void)reloadFetchedResults:(NSNotification*)note {
    NSLog(@"Underlying data changed ... refreshing!");

    //_fetchedResultsController=nil;
    //[self fetchedResultsController];

    [theTableView reloadData];


}

Any help will be greatly appreciated, Thanks!


Solution

  • Do you need to fetch another set of data, or are you looking to see changes to the same results set? If the former, tear it down and rebuild with a new predicate, fetch, etc. And perform fetch.

    If the latter, you need to merge your changes in with your moc. When you register for notifications, set it up like this:

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(documentContentsImportedChanges:) name:NSPersistentStoreDidImportUbiquitousContentChangesNotification object:self.managedObjectContext.persistentStoreCoordinator];
    
    
    - (void) documentContentsImportedChanges:(NSNotification*)notification
    {
        // Received updates from iCloud
        [self.managedObjectContext mergeChangesFromContextDidSaveNotification:notification];
    }