【问题标题】:Core Data sectionNameKeyPath Custom String核心数据 sectionNameKeyPath 自定义字符串
【发布时间】:2011-09-26 06:12:11
【问题描述】:

从 Core Data 中对对象表进行排序时,我想为包含属性的部分标题设置一个自定义字符串。例如,我希望部分名称显示“4 星”,而不仅仅是 4。我已经摆弄它,但如果我尝试将 sectionNameKeyPath 的字符串设置为除Entity Attribute 并且只有一个实体属性。以下是仅适用于属性的内容,并且注释掉了自定义中断字符串的少数尝试之一。

NSSortDescriptor *ratingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"starRating" ascending:NO];
    sortDescriptors = [NSArray arrayWithObjects:ratingDescriptor, nameDescriptor, nil];
    [ratingDescriptor release], ratingDescriptor = nil;
    // NSString *starSectionHeading = [NSString stringWithFormat:@"%d Stars", @"starRating"];
    // sectionKeyPath = starSectionHeading;
sectionKeyPath = @"starRating";

【问题讨论】:

    标签: iphone core-data attributes


    【解决方案1】:

    将您的 sectionNameKeyPath 设置为“starRating”,然后修改表格视图中的输出。 FRC 会在部分中对内容进行排序和整理,您只需更改通常显示为标题字符串的内容。

    - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section 
    {
        // Display the stars as section headings.
        int stars = [[[[fetchedResultsController sections] objectAtIndex:section] valueForKey:@"name"] intValue];
        if(stars == 1)
        {
            return @"1 Star"
        }
        else
        {
            return [NSString stringWithFormat:@"%u Stars", stars];
        }
    }
    

    我在一些以通用方式处理输出格式的表格视图中执行此操作(我将标题标题委托给另一个控制器类,给定第一个排序描述符路径和标题的值)。因此,您不仅限于像上面的代码那样对表格视图委托方法进行硬编码。

    您也有机会在这里本地化字符串,我必须在我的应用程序中处理 15 种本地化,并且在本地化时您必须考虑一些不同的事情。

    【讨论】:

    • 谢谢。它最接近我需要的东西。
    【解决方案2】:

    sectionNameKeyPath 应该是一个关键路径,即单个属性的名称或以单个属性终止的关系的名称。您正在尝试创建两个属性的组合,而 FRC 不自动支持该功能。

    要获得更花哨的东西,您必须继承 NSFetchedResultsController 的子类。 From the docs.

    如果你创建这个类的一个子类,如果 你想自定义创建 章节和索引标题。你 覆盖 sectionIndexTitleForSectionName:如果 您希望部分索引标题为 大写以外的东西 部分名称的第一个字母。你 如果你覆盖 sectionIndexTitles 希望索引标题成为某种东西 除了由创建的数组 打电话 sectionIndexTitleForSectionName: on 所有已知的部分。

    【讨论】:

      【解决方案3】:

      通过创建瞬态属性查看此答案: NSFetchedResultsController with sections created by first letter of a string

      只需更改一些名称并在您的委员会名称初始版本中替换:

      [[self committeeName] substringToIndex:1];
      

      [NSString stringWithFormat:@"%@ Stars", [self starRating]];
      

      【讨论】:

        【解决方案4】:
        (NSString *)tableView:(UITableView *)aTableView titleForHeaderInSection:(NSInteger)section
        {
            if ([self.fetchedResultsController sections].count > 0) {
                id <NSFetchedResultsSectionInfo> sectionInfo = 
                    [[self.fetchedResultsController sections] objectAtIndex:section];
                return [sectionInfo name];
            }
            return nil;
        }
        

        【讨论】:

          猜你喜欢
          • 2013-03-30
          • 2013-04-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-05-12
          • 1970-01-01
          • 1970-01-01
          • 2012-05-20
          相关资源
          最近更新 更多