Saturday, June 1, 2013

NSArray NSBinarySearchingLastEqual example in Objective C (iOS).

NSArray NSBinarySearchingLastEqual

Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.

enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
typedef NSUInteger NSBinarySearchingOptions;
Specifies that the search should return the first object in the range that is equal to the given object.
Specifies that the search should return the last object in the range that is equal to the given object.
Returns the index at which you should insert the object in order to maintain a sorted array.

NSArray NSBinarySearchingLastEqual example.
You can define a block as a global variable to get an effect similar to functions.

NSComparisonResult (^globalBlock)(id,id) = ^(id lhs, id rhs) {
    if([lhs intValue] < [rhs intValue]) {
        return (NSComparisonResult)NSOrderedAscending;
    } else if([lhs intValue] > [rhs intValue]) {
        return (NSComparisonResult)NSOrderedDescending;
    return (NSComparisonResult)NSOrderedSame;
Then, in the method doing the comparison:

int index1 = [array indexOfObject:number
                    inSortedRange:NSMakeRange(0, [array count])
                          options: NSBinarySearchingLastEqual
To put the block in a header, for external use:

NSComparisonResult (^globalBlock)(id,id);

Example of [NSArray NSBinarySearchingLastEqual].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
    inSortedRange:NSMakeRange(0, values.count)
    options: NSBinarySearchingLastEqual | NSBinarySearchingInsertionIndex
    usingComparator:^(id a, id b) {
        return [a compare:b];

NSArray NSBinarySearchingLastEqual example.
-(id) /* Getting */
    int location = [array indexOfObject:node
                                    inSortedRange:NSMakeRange(0, array.count)
                                          options: NSBinarySearchingLastEqual
                          ^ NSComparisonResult(id obj1, id obj2)
                              if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
                              if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
                              else return NSOrderedSame;
    if (location == NSNotFound) return nil;
    return [array objectAtIndex:location];

End of NSArray NSBinarySearchingLastEqual example article.