您应该只传递“名称”作为 sectionNameKeyPath。看到这个answer 到问题“Core Data backed UITableView with indexing”。
更新
该解决方案仅在您只关心拥有快速索引标题滚动器时才有效。在这种情况下,您将不会显示节标题。请参阅下面的示例代码。
否则,我同意 refulgentis 的观点,即瞬态属性是最佳解决方案。另外,在创建 NSFetchedResultsController 时,sectionNameKeyPath 有这个限制:
如果此密钥路径与
由第一个排序指定的
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];
//}
更新 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"];
并且,在 UITableViewDataSource 实现中取消注释 tableView:titleForHeaderInSection::
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo name];
}