0

You parse a property as a NSDictionary object in a MTLModel object, and then, you get the keys with allkeys method.

@interface SomeModel : MTLModel<MTLJSONSerializing>

@property (copy, nonatomic, readonly) NSDictionary *dictionary;

@end

...

NSArray *keys = [dictionary allkeys];

The returned keys are not usually sorted the same way they came in the HTTP response body.

For instance, the http response is this:

{"someObject":{"key1": "valueOfKey1", "key2": "valueOfKey2", "key3": "valueOfKey3",}}

but then, the NSDictionary keys are returned like this:

{"key2", "key1", "key3"}

How can you get the keys sorted as they came?

I have personally tested this, but it doesn't work:

[[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
Fran J Martínez
  • 236
  • 2
  • 12
  • Possible duplicate of [Can i sort the NSDictionary on basis of key in Objective-C?](https://stackoverflow.com/questions/3583020/can-i-sort-the-nsdictionary-on-basis-of-key-in-objective-c) – Alejandro Iván Oct 11 '17 at 13:15
  • 1
    The answer is you cant. You have to use sortedArrayUsingSelector or sortedArrayUsingComparator ans sort them according to NSComparisonResult. NSArray *sortedArray = [[dict allKeys] sortedArrayUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) { NSString *key1 = obj1; NSString *key2 = obj2; return [key2 compare:key1] == NSOrderedDescending; }]; – Reaper Oct 11 '17 at 20:46

0 Answers0