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實例。否則,這似乎是唯一的方法來做到這一點。