开发者

Can i sort the NSDictionary on basis of key in Objective-C?

开发者 https://www.devze.com 2023-01-13 22:10 出处:网络
Can I sort th开发者_高级运维e NSDictionary on basis of key?You can sort the keys and then create an NSMutableArray by iterating over them.

Can I sort th开发者_高级运维e NSDictionary on basis of key?


You can sort the keys and then create an NSMutableArray by iterating over them.

NSArray *sortedKeys = [[dict allKeys] sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *sortedValues = [NSMutableArray array];
for (NSString *key in sortedKeys)
    [sortedValues addObject: [dict objectForKey: key]];


It is much simpler to use objectsForKeys:notFoundMarker: for that

NSDictionary *yourDictionary;
NSArray *sortedKeys = [yourDictionary.allKeys sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"self" ascending:YES]]];
// As we using same keys from dictionary, we can put any non-nil value for the notFoundMarker, because it will never used
NSArray *sortedValues = [yourDictionary objectsForKeys:sortedKeys notFoundMarker:@""];
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号