Weakman10122 Weakman10122 - 26 days ago 10
Objective-C Question

Objective C NSDictionary: How can I sort my NSDictionary keys based on the key's value

I have an NSDictonary that equals the following value.

A = {
order = 3;
};
B = {
order = 1;
};
C = {
order = 2;
};


I need to sort keys A,B and C based on the order number from least to greatest. In this example, the keys should display as the following B,C and A. How Do I achieve this?

Answer

The order of keys of a NSMutableDictionary (A, B, C in your case) is decided by the system. You have no control of that.

But you can use NSMutableArray (not NSArray since that is immutable, i.e. cannot be modified) to achieve your goal. Each element in the array will be a separate NSDictionary with 2 key-value pairs - one for the key and one for the order, just to make things simpler.

This is the code you 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 are the results, how the modified array looks like:

array = (
        {
        key = B;
        order = 1;
    },
        {
        key = C;
        order = 2;
    },
        {
        key = A;
        order = 3;
    }
)