views:

21

answers:

1

I've created a table view of "log entries" which are organized into section based on the day they were entered.

I'm using Core Data so in order to do this I defined the following readonly calculated property in my NSManagedObject:

- (NSString *)formattedDay {
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setTimeStyle:NSDateFormatterNoStyle];
    [df setDateFormat:@"EEEE MMMM d, YYYY"];
    NSString *dateString = [df stringFromDate:self.timestamp];
    [df release];
    return dateString;
}

Then I use sectionNameKeyPath:@"formattedDay" in my NSFetchedResultsController.

This works fine but is a bit inefficient because a string must be formatted for every log row. Is there a way I can just have this return an NSDate (instead of a string) then somehow access the NSDate in titleForHeaderInSection:

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
    return sectionInfo.name;
}

Or somehow control how NSFetchedResultsController turns an NSDate into sectionInfo.name ?

+1  A: 

In my experience allocating NSDateFormatters many times is quite expensive, so you could try creating it as a singleton:

- (NSString *)formattedDay {
    static NSDateFormatter* sharedFormatter = nil;
    if( sharedFormatter == nil ) {
        sharedFormatter = [[NSDateFormatter alloc] init];
        [sharedFormatter setTimeStyle:NSDateFormatterNoStyle];
        [sharedFormatter setDateFormat:@"EEEE MMMM d, YYYY"];
    }
    return [sharedFormatter stringFromDate:self.timestamp];;
}

This will of course leak your NSDateFormatter, so you would have to release the instance from a static method somewhere else if you're pedantic :)

aegzorz
Thanks. I think I'll just make it static and lazily loaded in the method for now.
Nimrod