Reputation: 1637
I have name and distance fields in an array of data that I want to sort; I can sort by either one but not both together. I want the data sorted by name first, then distance, but when I use the two together, the sort is always on the first descriptor in the list, the second seems to get ignored.
NSSortDescriptor *nameSort = [[NSSortDescriptor alloc]
initWithKey:@"NAME"
ascending:YES
selector:@selector(localizedStandardCompare:)];
NSSortDescriptor *distanceSort = [[NSSortDescriptor alloc]
initWithKey:@"DISTANCE"
ascending:YES];
sortedArray = [featureSet.features sortedArrayUsingDescriptors:@[nameSort, distanceSort]];
[super.tableView reloadData];
Upvotes: 0
Views: 231
Reputation: 1440
The behavior you're seeing definitely makes sense - "A&W #0338" comes before "A&W #0339", so there is nothing more for the distance sort to determine.
If all of your data is structured this way - a name followed by #000 - you can strip the numbers off for your sort, and then your distance sort can do its job. You can either do that at the model layer by splitting your title into two properties, a name and location number, or you can do it inside of a sort descriptor.
NSSortDescriptor *nameSort = [NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES comparator:^NSComparisonResult(NSString *str1, NSString *str2) {
NSString *title1 = [[str1 componentsSeparatedByString:@" #"] firstObject];
NSString *title2 = [[str2 componentsSeparatedByString:@" #"] firstObject];
return [title1 compare:title2];
}];
If you use this nameSort and your distanceSort, "A&W #0338", "25 km" will come after "A&W #0339"
Upvotes: 1