Reputation: 109
I use a NSFetchedResultsController for populating a TableView. I want the sections to be sorted descending by date and the rows sorted ascending by date. Both use the key 'creation' and the sections have a transient property for the sectionNameKeyPath which returns a string for the date with the form: "Today, Yesterday, 20.11.2013, 19.11.2013, …" created from the 'creation' date. However, the rows are always sorted in the ordering of the first sort descriptor. Is this approach wrong?
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Exercise"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creation" ascending:NO],
[NSSortDescriptor sortDescriptorWithKey:@"creation" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.context
sectionNameKeyPath:@"localizedCreationDate"
cacheName:nil];
I am grateful for any provided help! br
UPDATE
The above approach can't work. :) I solved it by saving a second date as a property with the beginning of the day, ordered descending. This is also used as the sectionNameKeyPath. Additionally, for section header titles the localizedCreationDate is used.
- (void)setuptFetchedResultsController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"DNALoggedExercise"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDayDate" ascending:NO],
[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.context
sectionNameKeyPath:@"creationDayDate"
cacheName:nil];
}
Upvotes: 0
Views: 634
Reputation: 145
In your first piece of code, you're giving two contradictory NSSortDescriptors
, so only one is considered, and probably the first.
By creating a second date property just for convenience, you're introducing data duplication in your database, that's not a very good idea.
Why not sorting your results in whichever order, and just reading the array in reverse in cellForRowAtIndexPath
or titleForHeaderInSection
? Even better, why not having a small private method in your viewController that would prepare a NSDictionary or any other convenience data structure for later use?
Upvotes: 0