您应该只传递“name”作为sectionNameKeyPath。看到这个answer问题“核心数据支持带有索引的 UITableView”。
UPDATE
仅当您只关心快速索引标题滚动器时,该解决方案才有效。在这种情况下,您将不会显示节标题。请参阅下面的示例代码。
否则,我同意 refulgentis 的观点,即瞬态属性是最好的解决方案。另外,在创建 NSFetchedResultsController 时,节名键路径有这个限制:
如果此关键路径与
由第一个排序指定的
fetchRequest 中的描述符,它们必须
生成相同的相对顺序。
例如,第一个排序描述符
在 fetchRequest 中可能会指定密钥
对于持久性属性;
sectionNameKeyPath 可能指定一个键
对于源自以下的瞬态属性
持久性属性。
使用 NSFetchedResultsController 的样板 UITableViewDataSource 实现:
- (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”瞬态属性,将新的字符串属性添加到模型中的适用实体并选中“瞬态”框。
有几种方法可以实现 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"];
并且,取消注释tableView:titleForHeaderInSection:
在 UITableViewDataSource 实现中:
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}