NSFetchedResultsController ignores fetchLimit?

后端 未结 7 2046
春和景丽
春和景丽 2020-12-25 13:58

I have a NSFetchedResultsController to update a UITableView with content from Core Data. It\'s pretty standard stuff I\'m sure you\'ve all seen many times however I am runn

7条回答
  •  难免孤独
    2020-12-25 14:43

    I know this is an old question, but I have a solution for it:

    Since there is a known bug in NSFetchedResultsController that doesn't honor the fetchlimit of the NSFetchRequest, you have to manually handle the limiting of records within your UITableViewDataSource and NSFetchedResultsControllerDelegate methods.

    tableView:numberOfRowsInSection:

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
        id  sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    
        NSInteger numRows = [sectionInfo numberOfObjects];
    
        if (numRows > self.fetchedResultsController.fetchRequest.fetchLimit) {
    
            numRows = self.fetchedResultsController.fetchRequest.fetchLimit;
        }
    
        return numRows;
    }
    

    controller:didChangeObject:atIndexPath:forChangeType:newIndexPath:

    - (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath {
    
        switch(type) {
    
            case NSFetchedResultsChangeInsert:
    
                if ([self.tableView numberOfRowsInSection:0] == self.fetchedResultsController.fetchRequest.fetchLimit) {
                    //Determining which row to delete depends on your sort descriptors
                    [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:self.fetchedResultsController.fetchRequest.fetchLimit - 1 inSection:0]] withRowAnimation:UITableViewRowAnimationFade];
    
                }
    
                [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]
                                withRowAnimation:UITableViewRowAnimationFade];
            break;
            ...
        }
    }
    

提交回复
热议问题