我正在使用相当标准的fetchedResultsController实现来输出tableView.在-viewDidLoad的最后,我正在进行第一次调用:
NSError *error = nil; if (![[self fetchedResultsController] performFetch:&error]) { NSLog(@"Error! %@",error); abort(); }
这是我的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; }
我的tableView方法:
- (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; }
所以,问题是:
在_fetchedResultsController.fetchedobjects.count的日志中等于0,但在视觉上tableView充满了对象.为什么我有两个不同的计数结果?
解决方法
在您调用
performFetch:
之前,NSFetchedResultsController
实际上不会执行获取请求,因此结果计数为0.
如果在调用performFetch:之后记录fetchedobjects.count,您将看到一个与tableView行计数匹配的数字.