I am having trouble fetching results from Core Data that are sorted by date.
I have a DB table that contains football matches. Each match has a homeTeam, awayTeam and kickoffTime. The kickoffTime is an NSDate that stores the date and time the match will start.
I want to display the results of a query in a TableView divided into sections by the kickoff date. With the date as the section heading.
This is a little more complex than it might first appear. Due to differing time zones a match starting on one date in one part of the world is actually starting on a different date in another part of the world. So I can't simply ignore the times and store the kickoff dates in another column.
What I'm trying to do create a custom accessor that returns a formatted date, in whatever time zone the user is in, and then use this to sort and section the results. Here's my code in Match.h:
@dynamic kickoffTime;
@dynamic formattedKickoffTime;
@dynamic dateFormatter;
- (NSString *)formattedKickoffTime
{
[self willAccessValueForKey:@"kickoffTime"];
// Set the date formatter to the format we want to display the date
[dateFormatter setDateFormat:@"ccc, d MMM"];
// Format the date
NSString *myFormattedKickoffTime = [dateFormatter stringFromDate:[self kickoffTime]];
[self didAccessValueForKey:@"kickoffTime"];
// return the formatted date
return myFormattedKickoffTime;
}
- (NSDateFormatter *)dateFormatter
{
if (dateFormatter == nil)
{
dateFormatter = [[NSDateFormatter alloc] init];
}
return dateFormatter;
}
@end
However when I try to fetch and sort the data like so:
NSSortDescriptor *kickoffDescriptor = [[NSSortDescriptor alloc] initWithKey:@"formattedKickoffTime" ascending:YES];
...
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:appDelegate.managedObjectContext sectionNameKeyPath:@"formattedKickoffTime" cacheName:nil];
I get the following error message:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath formattedKickoffTime not found in entity <NSSQLEntity Match id=1>'
Would someone offer some advice please?