Saturday, June 1, 2013

NSMutableArray sortUsingSelector example in Objective C (iOS).


NSMutableArray sortUsingSelector

Sorts the array’s elements in ascending order, as determined by the comparison method specified by a given selector.

- (void)sortUsingSelector:(SEL)comparator

Parameters of [NSMutableArray sortUsingSelector]
comparator
A selector that specifies the comparison method to use to compare elements in the array.
The comparator message is sent to each object in the array and has as its single argument another object in the array. The comparator method should return NSOrderedAscending if the array is smaller than the argument, NSOrderedDescending if the array is larger than the argument, and NSOrderedSame if they are equal.

NSMutableArray sortUsingSelector example.
- (NSComparisonResult) compareSomeVariable:(GroupUser*) otherUser
{
    // Assumes ivar _someVariable is numeric; use NSString methods to compare
    // strings, etc.

    if(this->_someVariable < otherObject->_someVariable){
        return NSOrderedAscending;
    }
    else if(this->_someVariable > otherObject->_someVariable){
        return NSOrderedDescending;
    }
    else{
        return NSOrderedSame;
    }
}
and the sort them like this:

[array sortUsingSelector:@selector(compareSomeVariable:)];

Example of [NSMutableArray sortUsingSelector].
@interface NSNumber (CustomSorting)

- (NSComparisonResult)reverseCompare:(NSNumber *)otherNumber;

@end

@implementation NSMutableArray (CustomSorting)

- (NSComparisonResult)reverseCompare:(NSNumber *)otherNumber {
    return [otherNumber compare:self];
}

@end
And call it:

[highscores sortUsingSelector:@selector(reverseCompare:)];


NSMutableArray sortUsingSelector example.
-(NSArray *)testMethod:(NSArray *)arrayNumbers {   
    // 001
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    arrayNumbers = [NSArray arrayWithArray:sortedArray];
    return(arrayNumbers);  
}
.

-(NSArray *)testMethod:(NSArray *)arrayNumbers {   
    // 002
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    arrayNumbers = [[sortedArray copy] autorelease];
    return(arrayNumbers);  
}
.

-(NSArray *)testMethod:(NSArray *)arrayNumbers {   
    // 003
    NSMutableArray *sortedArray = [NSMutableArray arrayWithArray:arrayNumbers];
    [sortedArray sortUsingSelector:@selector(compare:)];
    return(sortedArray);   
}

End of NSMutableArray sortUsingSelector example article.