Lior Pollak
Lior Pollak

Reputation: 3450

Sorting NSMutableArray ascending (containing NSNumber)

I tried to search for how to sort an nsmutablearray but I only got confused more- how can I sort an NSMutableArray containing 10 NSNumbers (may be null) ascending, like this-

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

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

Thanks!

Upvotes: 0

Views: 1803

Answers (2)

Kyle Fang
Kyle Fang

Reputation: 1209

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

Mutable and word with [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;
}];

Upvotes: 2

Andrey Chernukha
Andrey Chernukha

Reputation: 21808

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

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

Upvotes: 2

Related Questions