2

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.

abbood
  • 21,507
  • 9
  • 112
  • 218
HurkNburkS
  • 5,332
  • 19
  • 93
  • 176

3 Answers3

2

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

Community
  • 1
  • 1
Bishal Ghimire
  • 2,430
  • 18
  • 37
0

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:)];
abbood
  • 21,507
  • 9
  • 112
  • 218
  • sorry abbood I should have explained that this is in a for loop so there are many objects. I was just trying to get the object type / structure across without complicating things to much. – HurkNburkS Sep 02 '13 at 02:52
  • i think you should update your question with the for loop in it.. b/c as it stands right now it doesn't make much sense.. – abbood Sep 02 '13 at 02:56
0

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"]];
}];
Andrew
  • 7,340
  • 3
  • 38
  • 47
  • i don't get it.. what is there to iterate through in `unSortedarray`.. it only has *one* object! – abbood Sep 02 '13 at 02:37