Skip to content

Instantly share code, notes, and snippets.

@ThinhPhan
Created June 30, 2015 19:26
Show Gist options
  • Save ThinhPhan/fda345627c4fa3174a74 to your computer and use it in GitHub Desktop.
Save ThinhPhan/fda345627c4fa3174a74 to your computer and use it in GitHub Desktop.
Fast enumerate NSDictionary with keys in order.
Example:
Input:
@{
1 = "A";
2 = "B";
3 = "C";
}
Output
@[
@{@"key": 1, @"value": @"A"};
@{@"key": 2, @"value": @"B"};
@{@"key": 3, @"value": @"C"};
]
// Approach 1: Sort keys in order first -> insert object with sorted keys
// Sort keys in order - Use 1 method below.
NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];
// OR
NSArray *sortedKeys = [[dictionary allKeys] sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options:NSNumericSearch];
}];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:[sortedKeys count]];
for (id key in sortedKeys) {
NSString *title = dictionary[key];
if(![title isEqualToString:@""]) {
[array addObject:title];
}
}
// Approach 2: Enumerate first -> sort array with keys in order.
NSMutableArray *array = [[NSMutableArray alloc] init];
[reasonsDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
NSDictionary *dic = [[NSDictionary alloc] initWithObjects:@[key, obj] forKeys:@[@"key", @"title"]];
[array addObject:dic];
}];
// Sort array of dictionary with value(s)
NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES];
array = [[array sortedArrayUsingDescriptors:@[descriptor]] copy];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment