fetchedResultsController.fetchedObjects.count = 0但它充满了对象

时间:2013-09-23 08:17:28

标签: ios objective-c uitableview core-data nsfetchedresultscontroller

我在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充满了对象。为什么我有两个不同的计数结果?

1 个答案:

答案 0 :(得分:13)

NSFetchedResultsController在您调用performFetch:之前实际上不会执行获取请求,因此结果计数为0.

如果在调用fetchedObjects.count后记录performFetch:,您将看到一个与tableView行数匹配的数字。