1. 程式人生 > >[iOS] How to sort NSMutableDictionary with dynamic keys?

[iOS] How to sort NSMutableDictionary with dynamic keys?

Sample 1:

NSArray *keys = [myDictionary allKeys];
keys = [keys sortedArrayUsingComparator:^(id a, id b) {
    return [a compare:b options:NSNumericSearch];
}];

NSLog(@"%@",keys);

Now fetch values based on the key sorted.

EDIT

To sort them in alphabetical order try this,

NSArray *keys = [myDictionary allKeys
]; keys = [[keys mutableCopy] sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; NSLog(@"%@",keys);

Sample 2:

Use this method:

- (NSArray *)sortKeysByIntValue:(NSDictionary *)dictionary {

  NSArray *sortedKeys = [dictionary keysSortedByValueUsingComparator:^NSComparisonResult(id obj1
, id obj2) { int v1 = [obj1 intValue]; int v2 = [obj2 intValue]; if (v1 < v2) return NSOrderedAscending; else if (v1 > v2) return NSOrderedDescending; else return NSOrderedSame; }]; return sortedKeys; }

Call it and then create a new dictionary with keys sorted by value:

NSDictionary *dictionary = [[NSDictionary alloc] initWithObjectsAndKeys:
                           @"4", @"dog",
                           @"3", @"cat",
                           @"6", @"turtle", 
                           nil];

NSArray *sortedKeys = [self sortKeysByIntValue:dictionary];
NSMutableDictionary *sortedDictionary = [[NSMutableDictionary alloc] init];

for (NSString *key in sortedKeys){
    [sortedDictionary setObject:dictionary[key] forKey:key];
}

Sampel 3:

Dictionaries are always unsorted. They are used as a key value storage to look up data. You should keep the order of your data separate from the dictionary. You need the dictionary you already have AND a sorted array of the keys.

@property NSDictionary *dataDict;
@property NSArray *sortedKeys;

self.sortedKeys = [self sortKeysByIntValue:self.dataDict];

In a UITableViewDataSource method, you would first consult your array with the index, get the key, and then retrieve the data from the dictionary.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger row = [indexPath row];
    NSString *key = [self.sortedkeys objectAtIndex:row];
    NSObject *dataObject = [self.dataDict valueForKey:key];