对NSMutableArray进行升序排序(包含NSNumber)

时间:2013-09-15 12:43:54

标签: nsarray

我试图搜索如何对nsmutablearray进行排序,但我只是更加困惑 - 如何对包含10个NSNumbers(可能为null)的NSMutableArray进行排序,像这样 -

NSMutableArray * a = [1,2,4,6,3,5,8,7,9,0]

到这 - a = [0,1,2,3,4,5,6,7,8,9]

谢谢!

2 个答案:

答案 0 :(得分:2)

NSArray *a = @[@0,@1,@5,@2];
a = [a sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [(NSNumber *)obj1 compare:obj2] == NSOrderedDescending;
}];

与[NSNull null]

的可变和单词
NSMutableArray *a = [@[@1,@2,@4,@6,@3,@5,@8,@7,@9,@0,[NSNull null]] mutableCopy];

[a sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    if (obj2 == [NSNull null]) {
        return YES;
    }
    return [(NSNumber *)obj1 compare:obj2] == NSOrderedDescending;
}];

答案 1 :(得分:2)

 NSArray *array = @[ @1, @2, @4, @6, @3, @5, @8, @7, @9, @0 ];

array = [array sortedArrayUsingSelector:@selector(compare:)];