Thursday, May 9, 2013

NSDictionary keysSortedByValueWithOptions example ios


keysSortedByValueWithOptions :usingComparator:

Returns an array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using a given comparator block and a specified set of options.
- (NSArray *)keysSortedByValueWithOptions:(NSSortOptions)optsusingComparator:(NSComparator)cmptr
Parameters
opts
A bitmask of sort options.
cmptr
A comparator block.
Return Value of [NSDictionary keysSortedByValueWithOptions]
An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr with the options given in opts.
Example of [NSDictionary keysSortedByValueWithOptions]
 NSArray *sortedKeys = [dictionary keysSortedByValueWithOptions:NSNumericSearch usingComparator:^NSComparisonResult(NSString *a, NSString *b){
        return [a compare:b];
    }];
    //Now you have an array of sorted keys


    NSMutableArray *sortedArray = [[NSMutableArray alloc] initWithCapacity:sortedKeys.count];
    for (NSString *key in sortedKeys){
        NSDictionary *dict = [NSDictionary dictionaryWithObject:[dictionary valueForKey:key] forKey:key];
        [sortedArray addObject:dict];
    }
    //Now you have a sortedArray of key-value pairs