带有格式化NSDate的NSFetchedResultsController titleForHeaderInSection

Dan*_*ger 5 iphone nsdate nsdateformatter nsfetchedresultscontroller

在我的Core Data应用程序中,我使用的是FetchedResultsController.通常在UITableView中为标题设置标题,您将实现以下方法,如下所示:

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

其中[sectionInfo name]返回NSString.

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

所以我想在这个上使用日期格式化程序来制作一个很好的标题,如"2010年4月17日",但我不能用[sectionInfo名称]做这个,因为这是NSString!有任何想法吗?

非常感谢

Dan*_*ger 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;
}
Run Code Online (Sandbox Code Playgroud)

请仔细看看,如果你知道更好的方法请说!

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