HurkNburkS
HurkNburkS

Reputation: 5510

sort NSDictionary based on single object key

I would like some help sorting an NSArray of NSDictionary values based on each objects ISV key.

This is the code I have so far for creating my array objects so you have a better idea of what I am trying to do.

NSArray *combinedKeysArray = [NSArray arrayWithObjects:@"HASM", @"ISL", @"ISV", nil];

valuesCombinedMutableArray = [NSMutableArray arrayWithObjects:[dict objectForKey:@"HASM"],
                                                              [dict objectForKey:@"ISL"],
                                                              [dict objectForKey:@"ISV"], 
                                                              nil];

combinedDictionary = [NSDictionary dictionaryWithObjects:valuesCombinedMutableArray
                                                 forKeys:combinedKeysArray];

[unSortedrray addObject:combinedDictionary];

// how do I then sort unSortedArray by the string values in each object ISV key?

any help would be greatly appreciated.

Upvotes: 2

Views: 945

Answers (3)

Andrew
Andrew

Reputation: 7719

You can use -sortedArrayUsingComparator: to sort any way you need.

[unSortedrray sortedArrayUsingComparator:^NSComparisonResult(NSDictionary *dict1, NSDictionary *dict2) {
    return [[dict1 objectForKey:@"ISV"] localizedCompare:[dict2 objectForKey:@"ISV"]];
}];

Upvotes: 0

abbood
abbood

Reputation: 23558

you won't be able to sort unSortedArray because it will only have one element in it (ie in your last line of code you are adding a single object by addObject).

That said, you cannot sort the dictionary either.. b/c dictionaries are unsorted by definition.

you can iterate over the keys of the dictionary in a specific order though, you can sort an array containing the keys of the dictionary.

NSArray *keys = [theDictionary allKeys];
NSArray *sortedKeys = [keys sortedArrayUsingSelector:@selector(compareMethod:)];

Upvotes: 0

Bishal Ghimire
Bishal Ghimire

Reputation: 2610

This can solve your problem How to sort an NSMutableArray with custom objects in it? https://stackoverflow.com/a/805589/1294448

You can use NSSortDescriptor to sort NSArays

Then in NSArray you have a method called sortedArrayUsingDescriptors

Or NSComparisonResult ca also be helpful some time http://developer.apple.com/DOCUMENTATION/Cocoa/Reference/Foundation/Classes/NSMutableArray_Class/Reference/Reference.html#//apple_ref/doc/uid/20000138-BABCEEJD

Upvotes: 2

Related Questions