Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort NSDictionary By property of object stored as value

I am storing data in NSMutableDictionary To store data received by web service.

I want to display data in alpha order but as we know Dictionary store data in their own way so I m getting different order for iOS 5 and iOS 6. iOS 5 it is fine but in iOS 6 it change order.

I am storing int key and object as value.

object contain ID,Name and Description.

EX:
  key  value
  1 -  (12,bhgjksd,kijdh)
  6 -  (13,kjfd,ikjk)
  2 -  (14,ljiuhbdf,dsjhfj)

How can I sort my Dictionary by Object.Name property. or get key based on Object.Name sorting order.

I don't want to sort on key I want to sort on Object.Name which is stored in value part as object.

Any kind of help is welcome..... Thanks in advance..

like image 821
CRDave Avatar asked Dec 06 '12 06:12

CRDave


2 Answers

Try this,

NSArray *sortedKeys = [dict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     return (NSComparisonResult)[obj1.name compare:obj2.name];;
}];

You will get all the keys in sortedKeys array, sorted in the order of object.name property. You can use these keys to get the values from dictionary as [dict valueForKey:[sortedKeys objectAtIndex:i]]. For more details please check apple documentation.

like image 84
iDev Avatar answered Nov 19 '22 23:11

iDev


NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"Object.Name" ascending:YES];
[items sortUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];

Also,

NSArray *ordered = [myDictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1, id obj2){
    return [obj1.name compare:obj2.name];
}];
like image 31
Anoop Vaidya Avatar answered Nov 19 '22 22:11

Anoop Vaidya