【问题标题】:NSFetchedResultsController titleForHeaderInSection with formatted NSDateNSFetchedResultsController titleForHeaderInSection 带有格式化的 NSDate
【发布时间】:2010-04-17 21:15:12
【问题描述】:

在我的核心数据应用程序中,我使用的是 FetchedResultsController。通常要在 UITableView 中设置标题的标题,您可以像这样实现以下方法:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 
    id <NSFetchedResultsSectionInfo> sectionInfo = [[<#Fetched results controller#> sections] objectAtIndex:section];
    return [sectionInfo name];
}

其中 [sectionInfo name] 返回一个 NSString。

我的 sectionKeyPath 基于 NSDate,除了它给我的部分标题是原始日期描述字符串(例如 12/12/2009 12:32:32 +0100)之外,这一切都很好,看起来有点像把标题弄乱了!

所以我想在此使用日期格式化程序来制作一个不错的标题,例如“2010 年 4 月 17 日”,但我不能使用 [sectionInfo name] 来做到这一点,因为这是 NSString!有什么想法吗?

非常感谢

【问题讨论】:

  • NSDateFormatter 的构建和执行非常昂贵;我会将它作为你的 tableview 的实例变量,这样你就不会在每次获取节标题时都构建它。

标签: iphone nsdate nsfetchedresultscontroller nsdateformatter


【解决方案1】:

我找到了解决办法:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    //Returns the title for each section header. Title is the Date.
    id <NSFetchedResultsSectionInfo> sectionInfo = [[fetchedResultsController sections] objectAtIndex:section];
    NSArray *objects = [sectionInfo objects];
    NSManagedObject *managedObject = [objects objectAtIndex:0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    NSDate *headerDate = (NSDate *)[managedObject valueForKey:@"itemDate"];
    NSString *headerTitle = [formatter stringFromDate:headerDate];
    [formatter release];
    return headerTitle;
}

请看这个,如果你知道更好的方法请说!

否则,如果您遇到类似的问题,我希望这会有所帮助!

【讨论】:

    【解决方案2】:

    在 iOS 4.0 及更高版本中,使用 [NSDateFormatterlocalizedStringFromDate] 类方法,您不必担心管理 NSDateFormatter 实例。否则这似乎是唯一的方法。

    【讨论】:

      【解决方案3】:

      这是答案的 Swift 版本:

      override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {        
          let sectionInfo = fetchedResultsController.sections![section]
          let objects = sectionInfo.objects
          if let topRecord:NSManagedObject = objects![0] as? NSManagedObject  {
              let formatter = DateFormatter()
              formatter.dateStyle = .medium
              return formatter.string(from: topRecord.value(forKey: "itemDate") as! Date)
          } else {
              return sectionInfo.indexTitle
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2011-09-17
        • 1970-01-01
        • 1970-01-01
        • 2011-06-08
        • 1970-01-01
        • 1970-01-01
        • 2021-08-05
        • 2012-01-05
        相关资源
        最近更新 更多