CRDave
CRDave

Reputation: 9285

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..

Upvotes: 6

Views: 2216

Answers (2)

Anoop Vaidya
Anoop Vaidya

Reputation: 46563

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];
}];

Upvotes: 3

iDev
iDev

Reputation: 23278

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.

Upvotes: 6

Related Questions