排序

 

排序简用

 

  NSMutableArray *mutarr = [[NSMutableArray alloc]init];
    NSArray *letters = @[@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z"];
        //create DATE
    for (int i = 0; i<10; i++) {
        NSString * name = [NSString stringWithFormat:@"%@%@%@",[letters objectAtIndex:arc4random()%25] ,[letters objectAtIndex:arc4random()%25],[letters objectAtIndex:arc4random()%25]];
        NSString *age = [NSString stringWithFormat:@"%u",arc4random()%80];
        
        NSMutableDictionary *person = [[NSMutableDictionary alloc]init];
        [person setValue:name forKey:@"name"];
        [person setValue:age forKey:@"age"];
        
        [mutarr   addObject:person];
    }
    NSLog(@"源数据 == %@",mutarr);

    //第一种
    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:NO];
    NSMutableArray *sortarr = [[NSMutableArray alloc]initWithObjects:&descriptor count:1];
    NSArray *sortedarr = [mutarr sortedArrayUsingDescriptors:sortarr];
    NSLog(@"sortedarr  %@",sortedarr);

    //第二种
    NSArray *sortedcomparr = [mutarr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        //字符串类
        return [obj1[@"name"] compare:obj2[@"name"]];
    }];
    NSLog(@"sortedcomparr    ===  %@",sortedcomparr);
    
    //第二种特例
    NSArray *sortedspecial = [mutarr sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        //数值比大小,使用上一种,7比17大
        if ([obj1[@"age"] integerValue] > [obj2[@"age"] integerValue]) {
            return NSOrderedAscending;
        }else{
            return NSOrderedDescending;
        }
    }];
    NSLog(@"sortedspecial    ===  %@",sortedspecial);

 

posted @ 2018-08-23 10:09  OIMMZC  阅读(149)  评论(0编辑  收藏  举报