开发者

Sort within a sorted Core Data fetch result?

So I have the following code that sorts a core data fetch by the "color" attribute.

sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:YES];
sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

Is there a way to take the result of that sort and now sub-sort by date (another attribute) within each color "group"?

Basically here's an example of what I get now...

RED - 11/1/2010
RED - 9/8/2010
RED - 11/9/2011
RED - 10/20/2011
GREEN - 11/1/2010
GREEN - 9/8/2010
GREEN - 11/9/2011
BLUE - 10/20/2011
BLUE - 11/1/2010
BLUE - 9/8/2010

And here's how I'd like the results to look...

RED - 9/8/2010
RED - 11/1/2010
RED - 10/20/2011
RED - 11/9/2011
GREEN - 9/8/2010
GREEN - 11/1/2010
GREEN - 11/9/2011
BLUE - 9/8/2010
BLUE - 11/1/2010
BLUE - 10/20/20开发者_高级运维11

I'm sure this can be done but I'm just not sure how to make it happen.


When you call SetSortDescriptors, pass through an array of all the NSSortDescriptors that you want to sort by. In your example you only created one sorting descriptor and only added the one to the sorting descriptors array. Create a second NSSortDescriptor for the date field, and also add that to your sort descriptors array. They're applied to the data set in the order they are in your array. See description below from apple documentation.

Something like this should work:

NSSortDescriptor *colorSort = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:asc selector:nil];
NSSortDescriptor *dateSort = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:asc selector:nil];
NSArray *sortDescriptors = [NSArray arrayWithObjects:colorSort, dateSort, nil];
[fetchRequest setSortDescriptors:sortDescriptors];

See these links: https://developer.apple.com/library/ios/documentation/Cocoa/Reference/CoreDataFramework/Classes/NSFetchRequest_Class/NSFetchRequest.html

https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSSortDescriptor_Class/Reference/Reference.html

Sets the array of sort descriptors of the receiver. - (void)setSortDescriptors:(NSArray *)sortDescriptors

sortDescriptors - The sort descriptors specify how the objects returned when the fetch request is issued should be ordered—for example by last name then by first name. The sort descriptors are applied in the order in which they appear in the sortDescriptors array (serially in lowest-array-index-first order).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜