Saturday, June 1, 2013

NSMutableArray sortWithOptions usingComparator example in Objective C (iOS).


NSMutableArray sortWithOptions usingComparator

Sorts the array using the specified options and the comparison method specified by a given NSComparator Block.

- (void)sortWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr

Parameters of [NSMutableArray sortWithOptions usingComparator]
opts
A bitmask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably).
cmptr
A comparator block.

NSMutableArray sortWithOptions usingComparator example.
[someArray sortWithOptions: 0 usingComparator: ^(id inObj1, id inObj2) {
    NSDate      *date1 = [NSDate dateWithString: [inObj1 objectForKey: @"dateString"]];
    NSDate      *date2 = [NSDate dateWithString: [inObj2 objectForKey: @"dateString"]];

    return [date1 compare: date2];
}];

Example of [NSMutableArray sortWithOptions usingComparator].
You can perform any arbitrarily complex sorting inline with NSMutableArray's sortWithOptions:usingComparator:

[myMutableArray sortWithOptions:NSSortStable usingComparator:^NSComparisonResult(NSString* str1, NSString* str2) {

    // Scan for your marker in both strings and split on it...
    // Say you store the results in substr1 and substr2...
    return [substr1 caseInsensitiveCompare:substr2];
}];

NSMutableArray sortWithOptions usingComparator example.
For example, let's consider the following:

NSMutableArray *array = [NSMutableArray arrayWithObjects:@"one", @"two", @"three", @"four", nil];
[array sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
    if ( [obj1 length] < [obj2 length] )
        return NSOrderedAscending;
    if ( [obj1 length] > [obj2 length] )
        return NSOrderedDescending;
    return NSOrderedSame;
}];

End of NSMutableArray sortWithOptions usingComparator example article.