I am trying to sort a mutableArray of NSDictionaries, currently I can do this by sorting with one objectForKey value, but the problem with this is that alot of these values can be the same so I need to have the other objectForKey to sort the array. I was wondering how, if the first objectForKey comparison returns an identical value, how I could then move onto a second objectForKey comparison and so on and so forth..
Currently I am doing this, which works.. but obviously only on the one key.
[dataArrayOfDictionaries sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
NSString *n1 = [d1 objectForKey:@"DESCRIPTION"];
NSString *n2 = [d2 objectForKey:@"DESCRIPTION"];
return [n1 localizedCompare:n2];
} ];
In my investigation I have tried this -
[dataArrayOfDictionaries sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2)
{
NSString *n1 = [d1 objectForKey:@"DESCRIPTION"];
NSString *n2 = [d2 objectForKey:@"DESCRIPTION"];
return [n1 localizedCompare:n2];
n1 = [d1 objectForKey:@"ID"];
n2 = [d2 objectForKey:@"ID"];
return [n1 localizedCompare:n2];
} ];
However this is not working as it sorts on description then completely resorted based off ID, I am wanting it if Description keys are the same to then sort those values by the ID key.. if that doesn't work then go down the list of Keys until its sorted.. I hope this makes sense.. any help would be highly appreciated.
You pretty much described the solution in your question: “if Description keys are the same to then sort those values by the ID key”. You can translate that English sentence directly into code:
[dataArrayOfDictionaries sortUsingComparator:^ NSComparisonResult(NSDictionary *d1, NSDictionary *d2) {
NSString *n1 = [d1 objectForKey:@"DESCRIPTION"];
NSString *n2 = [d2 objectForKey:@"DESCRIPTION"];
NSComparisonResult result = [n1 localizedCompare:n2];
if (result == NSOrderedSame) {
n1 = [d1 objectForKey:@"ID"];
n2 = [d2 objectForKey:@"ID"];
result = [n1 localizedCompare:n2];
}
return result;
}];
You could also perform the sort using two NSSortDescriptor objects:
[dataArrayOfDictionaries sortUsingDescriptors:[NSArray arrayWithObjects:
[NSSortDescriptor sortDescriptorWithKey:@"DESCRIPTION" ascending:YES
selector:@selector(localizedCompare:)],
[NSSortDescriptor sortDescriptorWithKey:@"ID" ascending:YES
selector:@selector(localizedCompare:)],
nil]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With