Thursday, May 9, 2013

NSDictionary keysSortedByValueUsingComparator example ios


keysSortedByValueUsingComparator:

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.
- (NSArray *)keysSortedByValueUsingComparator:(NSComparator)cmptr
Parameters
cmptr
A comparator block.
Return Value of [NSDictionary keysSortedByValueUsingComparator]
An array of the dictionary’s keys, in the order they would be in if the dictionary were sorted by its values using cmptr.
Example of [NSDictionary keysSortedByValueUsingComparator]
NSArray *sortedArray = [keySort keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

    NSString *p1 = [obj1 objectForKey:@"pos"];
    NSString *p2 = [obj2 objectForKey:@"pos"];

    if (p1 > p2 ) {
        return (NSComparisonResult)NSOrderedDescending;

    }

    if (p1 < p2) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
Example of [NSDictionary keysSortedByValueUsingComparator]
NSArray* sortedKeys = [stats keysSortedByValueUsingComparator:^(id first, id second) {

    if ( first < second ) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if ( first > second ) {
        return (NSComparisonResult)NSOrderedDescending;
    } else {
        return (NSComparisonResult)NSOrderedSame;
    }

  }];
Example of [NSDictionary keysSortedByValueUsingComparator]
SArray *myArray;

myArray = [myDict keysSortedByValueUsingComparator: ^(id obj1, id obj2) {

     if ([obj1 integerValue] > [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedDescending;
     }
     if ([obj1 integerValue] < [obj2 integerValue]) {

          return (NSComparisonResult)NSOrderedAscending;
     }

     return (NSComparisonResult)NSOrderedSame;
}];