当使用NSFetchedResultsController为UITableViewController创建节头时,fetchedResultsController.sections的每个项目都有一个对象而不是每个节。
//Set up the request
NSManagedObjectContext *context = self.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"Person"
inManagedObjectContext:context]];
[fetchRequest setFetchBatchSize:20];
NSSortDescriptor *sortDescriptor = nil;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName"
ascending:YES];
NSArray *sortDescriptors = nil;
sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[sortDescriptor release]; sortDescriptor = nil;
[fetchRequest setSortDescriptors:sortDescriptors];
[sortDescriptors release]; sortDescriptors = nil;
//setup fetch results controller
NSFetchedResultsController *controller = nil;
controller = [[NSFetchedResultsController alloc]
initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:@"firstName"
cacheName:@"PersonCache"];
__fetchedResultsController = controller;
[fetchRequest release]; fetchRequest = nil;
//IMPORTANT: Delete cache before changing predicate
[NSFetchedResultsController deleteCacheWithName:nil];
NSError *error = nil;
if (![controller performFetch:&error])
{
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
abort();
} else if ([[controller fetchedObjects] count] == 0){
[self retrievePeoples];
}
NSLog(@"result count: %i", [[controller fetchedObjects] count]);
NSLog(@"section count: %i", [[controller sections] count]);
NSLog(@"sectionIndexTitles count: %i", [[controller sectionIndexTitles] count]);
返回:
result count: 18
section count: 18
sectionIndexTitles count: 13
部分计数和sectionIndexTitles计数不应该匹配吗?当调用numberOfSectionsInTableView:和tableView:numberOfRowsInSection:方法时,我应该能够查看fetchedResultsController.section以获取计数而无需任何其他排序。
如何正确设置NSFetchResultsController以使sections数组中的每个对象都是针对每个部分而不是针对所有对象?
答案 0 :(得分:1)
Phillip Mills在另一个论坛上回答了这个问题。问题是我使用整个firstName来创建部分(而不仅仅是第一个字母)。修复是更新实体以在更新或更改时创建节标题。 Apple的DateSectionTitles有一个样本。