5

在我的核心数据应用程序中,我使用FetchedResultsController。通常设置为标题标题在一个UITableView你将实现像这样下面的方法:NSFetchedResultsController titleForHeaderInSection格式化NSDate

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

其中[sectionInfo名]返回的NSString。

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

所以我想用这个日期格式化程序来制作一个像“Apr 17 2010”这样好的标题,但是我不能用[sectionInfo name]这样做,因为这是NSString!有任何想法吗?

非常感谢

+0

NSDateFormatter的构建和执行相当昂贵;我会为你的tableview创建一个实例变量,所以你不会在每次获取节标题标题时都创建它。 – 2015-07-02 19:28:12

回答

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

请过目这一点,如果你知道一个更好的办法,请说!

否则,如果你坚持类似的问题,我希望这可以帮助!

1

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