Skip to content

Instantly share code, notes, and snippets.

@chisj
Created October 23, 2012 01:50
Show Gist options
  • Save chisj/3936202 to your computer and use it in GitHub Desktop.
Save chisj/3936202 to your computer and use it in GitHub Desktop.

Revisions

  1. chisj created this gist Oct 23, 2012.
    24 changes: 24 additions & 0 deletions sortArrayOfDictionary.m
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    void sortArrayOfDictionary {
    NSArray *arr = [NSArray arrayWithObjects:
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:5], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:2], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:7], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:2], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:1], @"a", [NSNumber numberWithInt:0], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:5], @"a", [NSNumber numberWithInt:1], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:6], @"a", [NSNumber numberWithInt:1], @"b",nil],
    [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:2], @"a", [NSNumber numberWithInt:9], @"b",nil],
    nil];
    NSLog(@"before sort the arr is:%@", arr);

    NSArray *sortedArray = [arr sortedArrayUsingComparator: ^(id obj1, id obj2) {
    if ( ([[obj1 objectForKey:@"a"] intValue] < [[obj2 objectForKey:@"a"] intValue]) || ([[obj1 objectForKey:@"a"] intValue] == [[obj2 objectForKey:@"a"] intValue] && [[obj1 objectForKey:@"b"] intValue] > [[obj2 objectForKey:@"b"] intValue] ) ) {
    return (NSComparisonResult)NSOrderedDescending ;
    } else {
    return (NSComparisonResult)NSOrderedAscending;
    }
    }];

    NSLog(@"after sort the arr is:%@", sortedArray);
    return;
    }