yun
yun

Reputation: 1283

sortedArrayUsingComparators not sorting numbers in ascending order

So this is probably really simple but I'm running into a problem with the sortedArrayUsingComparators method. I'm trying to sort an array of NSStrings that only contain number. For example, I have an array of strings: 0,1,2,3,4,5,6,7,10,8,9,11,12. When I run it using my code, I don't get a sorted result. In fact, I don't think the array changes order. Could someone help me out what I'm doing wrong here?

Here's the code snippet:

[tmp sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {

    NSInteger first = obj1.integerValue;
    NSInteger second = obj2.integerValue;

    if (first < second)
    {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    }
}];

Thanks!

Upvotes: 0

Views: 224

Answers (1)

Jeffery Thomas
Jeffery Thomas

Reputation: 42598

The value of tmp will not change, a new sorted array is returned.

Assuming tmp is an NSArray then try

tmp = [tmp sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {

    NSInteger first = obj1.integerValue;
    NSInteger second = obj2.integerValue;

    if (first < second)
    {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    }
}];

If tmp is an NSMutableArray then try -sortUsingComparator: instead of -sortedArrayUsingComparator:

[tmp sortUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2) {

    NSInteger first = obj1.integerValue;
    NSInteger second = obj2.integerValue;

    if (first < second)
    {
        return NSOrderedAscending;
    }
    else {
        return NSOrderedDescending;
    }
}];

Upvotes: 3

Related Questions