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

此代码可实现NSArray与NSDictionary的排序。 也可以解决NSString类型数据的排序问题。

    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]);

发表评论

电子邮件地址不会被公开。 必填项已用*标注

*