1

我想在 aUITableView的帮助下填充 a NSFetchedResultsController。我希望表格视图具有实体标题中第一个字母的部分。表格视图的右侧也应该有一个索引列表。

这是我的实体的样子:

@interface Book : NSManagedObject

@property (nonatomic, copy) NSString *title;

@end

我的第一个计划是拥有一个返回标题中第一个字母的瞬态属性:

- (NSString *)firstLetter
{
    // Edge-cases checking code not included
    return [self.title substringToIndex:1];
}

问题是它会给你不同的“2”和“3”部分,例如,我想要一个名为“#”的部分中的所有数字和符号,就像UILocalizedIndexCollation给你的一样。

但是哪些字母应该属于“#”类别?当然,这取决于语言,在英语中“Ö”应该属于另一个类别,但在瑞典语中它应该属于自己的类别。所以我想也许我应该NSLocalizedIndexCollation改用。这是该代码:

- (void)recalculateSectionizedBooks
{
    SEL selector = @selector(title);
    NSInteger sectionTitlesCount = [[[UILocalizedIndexedCollation currentCollation] sectionTitles] count];

    NSMutableArray *mutableSections = [NSMutableArray arrayWithCapacity:sectionTitlesCount];
    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++)
    {
        [mutableSections addObject:[NSMutableArray array]];
    }

    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Book"];
    NSError *error = nil;
    NSArray *result = [self.context executeFetchRequest:request
                                                  error:&error];
    if (error)
    {
        NSLog(@"Error fetching: %@", error);
    }

    for (Book *book in result)
    {
        NSInteger sectionNumber = [[UILocalizedIndexedCollation currentCollation] sectionForObject:book
                                                                           collationStringSelector:selector];
        [mutableSections[sectionNumber] addObject:book];
    }

    for (NSUInteger idx = 0; idx < sectionTitlesCount; idx++)
    {
        NSArray *objectsForSection = mutableSections[idx];
        mutableSections[idx] = [[UILocalizedIndexedCollation currentCollation] sortedArrayFromArray:objectsForSection
                                                                            collationStringSelector:selector];
    }

    self.sectionizedBooks = mutableSections;
}

它被调用-viewWillAppear:,之后我重新加载我的表格视图。数据源方法设置正确,并确保没有空白部分。

这个解决方案有两个问题。第一个是它需要大量的代码(比我向您展示的代码段要多得多)才能工作。第二个更严重的问题是性能很差。每次视图出现时,都必须重新计算部分,因为影响它的某些东西可能已经改变。10k 本书花了 30 秒,这是不可接受的。

我想我需要一个以巧妙的方式结合NSFetchedResultsController起来的解决方案。UILocalizedCollation这是我需要的解决方案:

  • 根据标题中的第一个字母将书籍分成几部分
  • 最后应该存在一个“其他”类别('#')
  • 没有空白部分
  • 右侧的索引列表,所有可能的字母 + '#' 最后
  • 高性能,至少在第一次出现视图之后
4

0 回答 0