NSArray与NSDictionary的排序代码分享。同样适用于NSString类的数据

来源:互联网 发布:seo编辑招聘 编辑:程序博客网 时间:2024/05/29 14:00
NSArray *array = [NSArray arrayWithObjects:
                  [NSDictionary dictionaryWithObjectsAndKeys:
                                            @"1.0",@"One",
                                            @"2.0",@"Two",
                                            @"3.0",@"Three",
                                            nil],
                  [NSDictionary dictionaryWithObjectsAndKeys:
                   @"1.1",@"One",
                   @"2.1",@"Two",
                   @"3.1",@"Three",
                   nil],
                  [NSDictionary dictionaryWithObjectsAndKeys:
                   @"1.3",@"One",
                   @"2.3",@"Two",
                   @"3.3",@"Three",
                   nil]
                  , nil];
 
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"Two" ascending:NO comparator:^(id obj1, id obj2) {
    if ([obj1 floatValue] > [obj2 floatValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    }
    if ([obj1 floatValue] < [obj2 floatValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    }
    return (NSComparisonResult)NSOrderedSame;
}];
 
[array sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
 
NSLog@("[array objectAtIndex:1] = %@",[array objectAtIndex:1]);