FetchedResultsController.fetchedObjects.count = 0, but it is full of objects

I use the pretty standard implementation of fetchedResultsController to output to tableView . At the end of -viewDidLoad I make the first call:

 NSError *error = nil; if (![[self fetchedResultsController] performFetch:&error]) { NSLog(@"Error! %@",error); abort(); } 

this is my fetchedResultsController:

  - (NSFetchedResultsController *) fetchedResultsController { if (_fetchedResultsController != nil) { return _fetchedResultsController; } NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; NSEntityDescription *entity = [NSEntityDescription entityForName:@"Preparation" inManagedObjectContext:_context]; [fetchRequest setEntity:entity]; int i = 1; NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ismer == %d", i]; fetchRequest.predicate = predicate; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]; NSArray *sortDescriptors = [[NSArray alloc] initWithObjects: sortDescriptor, nil]; fetchRequest.sortDescriptors = sortDescriptors; _fetchedResultsController = [[NSFetchedResultsController alloc]initWithFetchRequest:fetchRequest managedObjectContext:_context sectionNameKeyPath:nil cacheName:nil]; _fetchedResultsController.delegate = self; NSLog(@"_fetchedResultsController.fetchedObjects.count - %d", _fetchedResultsController.fetchedObjects.count); return _fetchedResultsController; } 

my tableView methods:

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return [[self.fetchedResultsController sections]count]; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { id <NSFetchedResultsSectionInfo> secInfo = [[self.fetchedResultsController sections] objectAtIndex:section]; return [secInfo numberOfObjects]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } CDPreparation *drug = (CDPreparation *)[self.fetchedResultsController objectAtIndexPath:indexPath]; cell.textLabel.text = [NSString stringWithFormat:@"%@", drug.name]; return cell; } 

So the question is:

in log _fetchedResultsController.fetchedObjects.count is 0, but visually the tableView populated with objects. Why do I have two different results for counting?

+7
ios objective-c uitableview core-data nsfetchedresultscontroller
source share
1 answer

NSFetchedResultsController does not actually execute a select query until you call performFetch: so the number of results is 0.

If you enter fetchedObjects.count after calling performFetch: you will see a number corresponding to the count of the tableView row.

+12
source share

All Articles