您应该只传递"name"作为sectionNameKeyPath.请参阅这answer个问题"核心数据备份UITableView与索引".
UPDATE
否则,我同意refulgentis的观点,即瞬态特性是最佳解决方案.此外,在创建NSFetchedResultsController时,sectionNameKeyPath具有以下限制:
如果此密钥路径与
样板文件UITableViewDataSource使用NSFetchedResultsController实现:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[fetchedResultsController sections] count];
}
- (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [fetchedResultsController sectionIndexTitles];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
return [fetchedResultsController sectionForSectionIndexTitle:title atIndex:index];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
// Don't implement this since each "name" is its own section:
//- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
// id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
// return [sectionInfo name];
//}
UPDATE 2
对于新的"uppercaseFirstLetterOfName"瞬态属性,向模型中的适用实体添加一个新字符串属性,并选中"transient"框.
有几种方法可以实现getter.如果要生成/创建子类,则可以将其添加到子类的实现(.m)文件中.
否则,您可以在NSManagedObject上创建一个类别(我将其放在我的视图控制器的实现文件的顶部,但您可以将其拆分为适当的头文件和它自己的实现文件):
@interface NSManagedObject (FirstLetter)
- (NSString *)uppercaseFirstLetterOfName;
@end
@implementation NSManagedObject (FirstLetter)
- (NSString *)uppercaseFirstLetterOfName {
[self willAccessValueForKey:@"uppercaseFirstLetterOfName"];
NSString *aString = [[self valueForKey:@"name"] uppercaseString];
// support UTF-16:
NSString *stringToReturn = [aString substringWithRange:[aString rangeOfComposedCharacterSequenceAtIndex:0]];
// OR no UTF-16 support:
//NSString *stringToReturn = [aString substringToIndex:1];
[self didAccessValueForKey:@"uppercaseFirstLetterOfName"];
return stringToReturn;
}
@end
此外,在此版本中,不要忘记将"uppercaseFirstLetterOfName"作为sectionNameKeyPath传递:
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext
sectionNameKeyPath:@"uppercaseFirstLetterOfName" // this key defines the sections
cacheName:@"Root"];
要在UITableViewDataSource实现中取消注释tableView:titleForHeaderInSection:
:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}