Sorting as a result of a sorted result of fetching kernel data?

So, I have the following code that sorts a sample of kernel data using 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 this view and now sort by date (another attribute) in each color "group"?

Basically, here is an example of what I'm getting 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 is how I would 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/2011 

I'm sure it can be done, but I'm just not sure how to do it.

+4
source share
1 answer

When you call SetSortDescriptors, pass an array of all the NSSortDescriptors that you want to sort. In your example, you created only one sort descriptor and only add it to the sort descriptor array. Create a second NSSortDescriptor for the date field, and add it to the array of sort descriptors. They apply to the dataset in the order in which they are in your array. See the description below from the 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 recipient sort descriptors. - (void) setSortDescriptors: (NSArray *) sortDescriptors

sortDescriptors - sorting descriptors determine how the objects returned when issuing a query for sorting should be ordered, for example, by name and then by name. Sort descriptors are applied in the order in which they appear in the sortDescriptors array (sequentially in the order of the lowest-order-first-order index-array).

+10
source

Source: https://habr.com/ru/post/1347409/


All Articles