NSFetchedResultsController with sections sorted by TWO criteria
I have a table view that displays a musician's albums. Each section is an Album, each row is a Track. I need the albums/sections sorted by release date, then by title. I'm pulling the tracks from Core Data like so:
fetchRequest = [[NSFetchRequest alloc] init];
...
fetchRequest.sortDescriptors = [NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:@"album.releaseDate" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:@"album.title" ascending:YES],
[NSSortDescriptor sortDescriptorWithKey:@"trackNumber" ascending:YES],
nil];
frc = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:context
sectionNameKeyPath:@"album.releaseDate" // <-- PROBLEM HERE
cacheName:nil];
This doesn't work because two albums with the same release date will appear in the same section.
If I use album.title as the sectionNameKeyPath, hell breaks loose because the sections are sorted alphabetically, then imposed on the tracks (which are sorted by date, title, trackNumber).
How do I sort the sections by date, then by title?
From what I've read, this single-property sorting is just something we have to live with on iOS. So I added a transient property to Album that acts as a sort key for both properties:
- (NSString *)sortKeyDateTitle
{
[self willAccessValueForKey:@"sortKeyDateTitle"];
NSString *sortKey = [NSString stringWithFormat:@"%@%@", self.releaseDate, self.title];
[self didAccessValueForKey:@"sortKeyDateTitle"];
return sortKey;
}
It produces strings like this:
1954-04-01 06:00:00 +0000A Night At Birdland, Vol. 1
1954-04-01 06:00:00 +0000A Night At Birdland, Vol. 2
It works, but converting from date to string for sorting seems stupid. I'm waiting for something better.
链接地址: http://www.djcxy.com/p/36156.html