Saturday, June 1, 2013

NSArray sortedArrayWithOptions usingComparator example in Objective C (iOS).


NSArray sortedArrayWithOptions usingComparator

Returns an array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified by a given NSComparator Block.

- (NSArray *)sortedArrayWithOptions:(NSSortOptions)opts usingComparator:(NSComparator)cmptr

Parameters
opts
A bit mask that specifies the options for the sort (whether it should be performed concurrently and whether it should be performed stably).
cmptr
A comparator block.

Return Value of [NSArray sortedArrayWithOptions usingComparator]
An array that lists the receiving array’s elements in ascending order, as determined by the comparison method specified cmptr.

NSArray sortedArrayWithOptions usingComparator example.
NSArray* sorted = [unsorted sortedArrayWithOptions:0 usingComparator:^(id v1, id v2) {
  float f1 = [v1 floatValue];
  float f2 = [v2 floatValue];

  if (f1 == f2) return NSOrderedSame;
  return (f1 < f2) ? NSOrderedAscending : NSOrderedDescending;
}];

Example of [NSArray sortedArrayWithOptions usingComparator].
NSArray *test = @[@"Å", @"A", @"B"];
NSLocale *swedish = [[NSLocale alloc] initWithLocaleIdentifier:@"sv"];

NSArray *sortedTest = [test sortedArrayWithOptions:0
                                   usingComparator:^(NSString  *v1, NSString *v2) {
    return [v1 compare:v2 options:NSCaseInsensitiveSearch
                 range:NSMakeRange(0, [v1 length])
                locale:swedish];
}];

// Output: A, B, Å

NSArray sortedArrayWithOptions usingComparator example.
- (NSArray *)subDocumentsOrdered
{
if (!subDocumentsOrdered)
{
subDocumentsOrdered = [[[[self subDocument] allObjects] sortedArrayWithOptions:NSSortStable|NSSortConcurrent usingComparator:(NSComparator) ^(SubDocument *stroke1, SubDocument *stroke2)
                          {
                              return [[stroke1 date] compare:[stroke2 date]];
                          }
                          ] mutableCopy];
}
    return subDocumentsOrdered;
}

End of NSArray sortedArrayWithOptions usingComparator example article.