ios - Objective C NSDictionary: How can I sort my NSDictionary keys based on the key's value -
i have nsdictonary equals following value.
= { order = 3; }; b = { order = 1; }; c = { order = 2; };
i need sort keys a,b , c based on order number least greatest. in example, keys should display following b,c , a. how achieve this?
the order of keys of nsmutabledictionary (a, b, c in case) decided system. have no control of that.
but can use nsmutablearray (not nsarray since immutable, i.e. cannot modified) achieve goal. each element in array separate nsdictionary 2 key-value pairs - 1 key , 1 order, make things simpler.
this code need:
nsmutablearray *arrayofdictionaries = [@[ @{ @"key" : @"a", @"order" : @3 }, @{ @"key" : @"b", @"order" : @1 }, @{ @"key" : @"c", @"order" : @2 }, ] mutablecopy]; [arrayofdictionaries sortusingcomparator:^nscomparisonresult(id _nonnull obj1, id _nonnull obj2) { nsnumber *number1 = obj1[@"order"]; nsnumber *number2 = obj2[@"order"]; return [number1 compare:number2]; }]; nslog(@"array = %@", arrayofdictionaries);
these results, how modified array looks like:
array = ( { key = b; order = 1; }, { key = c; order = 2; }, { key = a; order = 3; } )
Comments
Post a Comment