iPhone Programmatically iPhone Programmatically - 2 months ago 7
iOS Question

Sort NSDictionary in ascending order

I am trying to sort an

NSDictionary
in ascending order. I am using this code:

NSDictionary *valDict = self.mGetDataDict[key][rowKey];

for (NSString *valueKey in
[[valDict allKeys] sortedArrayUsingSelector:@selector(compare:)])
{
if ([valueKey isEqualToString:@"attr"])
{
dictRow = self.mGetDataDict[key][rowKey][valueKey];
}
else {
NSString *valKey = self.mGetDataDict[key][rowKey][valueKey];
[arrSeatsStatus addObject:valKey];
}
}


This is the output I'm getting:

1 = off;
10 = off;
2 = on;
3 = on;
4 = on;
5 = on;
6 = on;
7 = on;
8 = on;
9 = on;


This is the required output:

1: "off",
2: "on",
3: "on",
4: "on",
5: "on",
6: "on",
7: "on",
8: "on",
9: "on",
10: "off"


The required output is an actual value coming from JSON.

Answer

You can use NSSortDescriptor like this:

NSArray* array1 = @[@"1 = off", @"10 = off", @"2 = on", @"3 = on"];
NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"" ascending:YES selector:@selector(localizedStandardCompare:)];

NSLog(@"Ordered array: %@", [array1 sortedArrayUsingDescriptors:@[ descriptor ]]);

which produces this output:

2013-06-04 12:26:22.039 EcoverdFira[3693:c07] Ordered array: (
  "1 = off",
  "2 = on",
  "3 = on",
  "10 = off"
)

There's a good article on NSSortedDescriptor's here.

Comments