views:

258

answers:

3

In my Core Data app I am using a FetchedResultsController. Usually to set titles for headers in a UITableView you would implement the following method like so:

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

where [sectionInfo name] returns a NSString.

my sectionKeyPath is based on an NSDate and this all works fine apart from the section headers it gives me are the raw date description strings (e.g. 12/12/2009 12:32:32 +0100) which look a bit of a mess in a header!

So I want to use a date formatter on this to make a nice header like "Apr 17 2010" but I can't do that with the [sectionInfo name] as this is NSString! Any Ideas?

Many Thanks

A: 

I found a solution:

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

Please look over this, if you know of a better way please say!

Otherwise if your stuck with a similar problem I hope this helps!

Daniel Granger
+1  A: 

The NSDateFormatter is pretty expensive to build and execute; I'd make that an instance variable of your tableview so you're not building it each time you grab a section header title.

A: 

I have a similar problem. But I would like to have the entry sorted by date and time in the tableview but only by the date without the time in sections, since it makes a new section for every entry if its sorted by time as well.

If I use a dateformatter, it changes the title so it looks nice, but leaves many duplicate sections.

Does anyone know a solution to this?

Mike