【问题标题】:Setting UITableView headers from NSFetchedResultsController从 NSFetchedResultsController 设置 UITableView 标头
【发布时间】:2010-11-07 19:47:25
【问题描述】:

我有一个NSFetchedResultsController,它正在从NSManagedObjectContext 获取对象。我正在使用结果来填充 UITableView。

我正在使用这两个排序描述符进行过滤。

NSSortDescriptor *lastOpened = 
    [[NSSortDescriptor alloc] initWithKey:@"lastOpened" ascending:NO];

NSSortDescriptor *titleDescriptor = 
    [[NSSortDescriptor alloc] initWithKey:@"title" ascending:YES];

当我创建NSFetchedResultsController 时,我通过sectionNameKeyPath:@"lastOpened" 对部分进行排序。

现在我的部分显示标准格式,如 2009-07-02 20:51:27 -0400,由于不能同时打开两个,它们都是唯一的。我需要它们涵盖日期/时间范围,例如一整天,并采用人类可读的形式。像7 月 2 日星期四

谢谢!


编辑:

这一切都在UITableViewController 中。这里还有一些代码。

- (NSString *)tableView:(UITableView *)tableView  titleForHeaderInSection:(NSInteger)section {
    // Display the dates as section headings.
    return [[[fetchedResultsController sections] objectAtIndex:section] name];
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    return [sectionInfo numberOfObjects];
}

【问题讨论】:

  • 您是使用绑定来填充表格还是为 UITableView 编写了数据源?
  • 提问者是为 iPhone 开发的,所以不能是 Bindings,因为 Cocoa Touch 中不存在。 developer.apple.com/IPhone/library/documentation/Miscellaneous/…
  • 您应该通过将 NSPredicates 设置为 Fetched 结果控制器来过滤掉结果,顺便说一句。您仍然可以使用多种方式进行排序,但如果您只想显示某些“属性为真”(即满足谓词)的某些对象,请使用 NSPredicates。

标签: iphone cocoa cocoa-touch core-data


【解决方案1】:

我最终将一个新属性 day 添加到我的 NSManagedObject 子类中以获取格式化的日期字符串。

@property (nonatomic, readonly) NSString * day;
@property (nonatomic, retain) NSDateFormatter * dateFormatter

合成 dateFomatter。 @synthesize dateFormatter;

我在 awakeFromFetch 和 awakeFromInsert 中初始化日期格式化程序。

self.dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[self.dateFormatter setDateStyle:NSDateFormatterMediumStyle];

day 的访问器。

- (NSString *)day {
  NSDate *date = self.startDate;
  return [self.dateFormatter stringFromDate:date];
}

然后我将我的部分名称键路径设置为查看day;您不需要对排序描述符进行任何更改。

【讨论】:

    【解决方案2】:

    我还没有机会深入研究 SDK 的那个领域(我的工作是使用 C#,所以 iPhone 的东西是我的业余爱好),但据我所知,你会想要使用另一个init,特别是 initWithKey:ascending:selector: 对于选择器,您可以将选择器传递给您的比较方法,该方法仅在年/月/日进行比较,忽略时间。

    这里是参考网址:iPhone Library Documentation

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多