5

在我的核心数据应用程序中,我使用的是 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!有任何想法吗?

非常感谢

4

3 回答 3

14

我找到了一个解决方案:

- (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;
}

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

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

于 2010-04-17T21:54:05.187 回答
1

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

于 2011-04-13T02:00:17.350 回答
0

这是答案的 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
    }
}
于 2018-04-04T19:48:28.943 回答