Koen Koen - 19 days ago 5
iOS Question

fetchedObjects is nil after performFetch, but tableView has data

I have a working

UITableView
backed by
Core Data
.

I am now implementing a feature that when the table is empty, I disable the
rightBarButtonItem
:

- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: animated];

self.navigationItem.rightBarButtonItem.enabled = self.fetchedResultsController.fetchedObjects ? YES : NO;
}


But even when the table has items,
self.fetchedResultsController.fetchedObjects
returns nil, so the button is always disabled.

I call
performFetch
in
viewDidLoad
.

I tried this code inside viewDidLoad, but the same happens.

Why is
self.fetchedResultsController.fetchedObjects
nil, even when the table is populated?

EDIT added more code

Items are generated immediately into a child context before showing the table. The same context is used for the
fetchRequest
.

The items are definitely in the context, since the table gets populated with the items in the child context. However, when calling
viewWillAppear
,
self.fetchedResultsController.fetchedObjects
is still nil.

This is how I call
performFetch
(in
viewDidLoad
):

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSError *error = nil;
if (![self.fetchedResultsController performFetch: &error])
{
NSLog(@"Failed to perform fetch: %@", error);
}

dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
});


I am saving the context before showing the VC.

Answer

Have you tried calling self.fetchedResultsController.fetchedObjects in your dispatchBlock like this

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
 NSError *error = nil;
 if (![self.fetchedResultsController performFetch: &error])
 {
      NSLog(@"Failed to perform fetch: %@", error);
 }

 dispatch_async(dispatch_get_main_queue(), ^{
            self.navigationItem.rightBarButtonItem.enabled = self.fetchedResultsController.fetchedObjects ? YES : NO;
            [self.tableView reloadData];
     });
    });