Search code examples
iosobjective-cnsmutablearraynsmutabledictionary

How to sort an NSMutableArray of NSMutableDictionaries using mutiple objectForKey


I have a NSmutableArray with dozens of NSMutableDictionaries in it.

Each NSMutableDictionary looks something like this:

insComp = F;
insFlow = "suVE";
inID = "SJF42B";
ID = 10000038;

I would then like to know how I sort ascending values by several of the NSDictionary keys. for each object instance.

insComp > inID > ID

for example, not using same keys or values

-- obj1
var1 = A
var2 = A

-- obj2
var1 = A
var2 = B

-- obj3
var1 = B
var2 = A

-- obj4
var1 = C
var2 = A

So that would be sorting first by var1 then every var1-var2 is sorted and so on. I think it's referred to as a tree sort?


Solution

  • You should try going with NSPredicate and NSSortDescriptor classes

    NSArray *sortedArray = [yourArray sortedArrayUsingDescriptors:
                               @[[NSSortDescriptor 
                                 sortDescriptorWithKey:@"insComp" ascending:YES], 
                                 [NSSortDescriptor
                                 sortDescriptorWithKey:@"Id" ascending:YES]]];
    

    There is a nice tutorial dedicated to sorting and filtering and all such kind operations on data collection classes in objective c here.