Sorting NSArray of dictionaries by value of a key in the dictionaries
I think this will do it:
brandDescriptor = [[NSSortDescriptor alloc] initWithKey:@"brand" ascending:YES];sortDescriptors = [NSArray arrayWithObject:brandDescriptor];sortedArray = [myArray sortedArrayUsingDescriptors:sortDescriptors];
I pulled the code from Sort Descriptor Programming Topics. Also, Key-Value Coding comes into play, in that sortedArrayUsingDescriptors:
will send a valueForKey:
to each element in myArray
, and then use standard comparators to sort the returned values.
We Got The Solution By Using The Method Follows
[self.jsonData sortUsingDescriptors: [NSArray arrayWithObjects: [NSSortDescriptor sortDescriptorWithKey:"fullname" ascending:YES], [NSSortDescriptor sortDescriptorWithKey:"id" ascending:NO], nil]];
Where:-
jsonData
- MutableArray Which holds the Parsed JSON Data.
fullname
- the data we want to sort.
id
- An unique data which comes with the inner dictionary.
arrSorted = [arrBrand sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) { if ([[obj1 valueForKey:@"iUserId"] integerValue] > [[obj2 valueForKey:@"iUserId"] integerValue]) { return (NSComparisonResult)NSOrderedDescending; } if ([[obj1 valueForKey:@"iUserId"] integerValue] < [[obj2 valueForKey:@"iUserId"] integerValue]) { return (NSComparisonResult)NSOrderedAscending; } return (NSComparisonResult)NSOrderedSame; }];