好的。这是与此处完全相同的问题:Why is NSFetchedResultsController loading all rows when setting a fetch batch size?
但是他的解决方案并不能解决我的问题。
我有一个有几千条记录的屏幕,加载它们的速度很慢。我将批处理大小设置为 30(大约是屏幕上单元格的三倍),但由于某种原因,它仍然循环并加载所有批处理。
这是代码
- (NSFetchedResultsController *)guestCardFetchedResultsController
{
if (guestCardFetchedResultsController != nil) {
return guestCardFetchedResultsController;
}
// SELECT * from GuestCard
NSFetchRequest* fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"GuestCard" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
// ORDER BY updated DESC
NSSortDescriptor* updatedSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"created" ascending:NO];
[fetchRequest setSortDescriptors:@[updatedSortDescriptor]];
fetchRequest.fetchBatchSize = 30;
NSString *cacheName = self.isReportProblemView ? @"reportProblemGuestCardsAll" : @"guestCardsAll";
[NSFetchedResultsController deleteCacheWithName:cacheName];
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.context sectionNameKeyPath:@"sectionIdentifier" cacheName:cacheName];
aFetchedResultsController.delegate = self;
self.guestCardFetchedResultsController = aFetchedResultsController;
// Clean up
NSError *error = nil;
if (![[self guestCardFetchedResultsController] performFetch:&error]) {
}
return self.guestCardFetchedResultsController;
}
在这种情况下,我没有做任何非常有趣的事情。这是一些委托代码(不包括单元格创建,我确认仅调用屏幕上的单元格数量):
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
if ([self.guestCardFetchedResultsController.fetchedObjects count] == 0) {
return 1;
}
// Return the number of sections.
return [[self.guestCardFetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.guestCardFetchedResultsController.fetchedObjects count] == 0) {
return 1;
}
// Return the number of rows in the section.
id <NSFetchedResultsSectionInfo> sectionInfo = [guestCardFetchedResultsController sections][section];
return [sectionInfo numberOfObjects];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
if ([self.guestCardFetchedResultsController.fetchedObjects count] == 0) {
return @"";
}
return [[self.guestCardFetchedResultsController sections][section] name];
}