Search code examples
objective-cnsstringnsarraylastindexof

What is the Objective-C equivalent of Array.lastIndexOf(element, fromIndex)


I come from a JavaScript/ActionScript background and am used to doing indexOf and lastIndexOf on strings and arrays. For NSStrings, both of these were relatively simple:

// equivalent of JavaScript's string.indexOf(substring, fromIndex)
[string rangeOfString:substring
              options:nil
                range:NSMakeRange(fromIndex, string.length - fromIndex)].location;

// equivalent of JavaScript's string.lastIndexOf(substring, fromIndex)
[string rangeOfString:substring 
              options:NSBackwardsSearch 
                range:NSMakeRange(string.length - fromIndex, fromIndex)].location;

For NSArrays, I managed to figure out indexOf, but couldn't find a native function to do lastIndexOf:

// equivalent of JavaScript's array.indexOf(item, fromIndex)
[array indexOfObject:item 
             inRange:NSMakeRange(fromIndex, array.count - fromIndex)];

What would be the code to find the lastIndexOf an element in an array within a range? Will it require more than a single selector call?


Solution

  • It can be done with a single method call to -[NSArray indexOfObjectWithOptions:passingTest:], though it requires passing a block.

    [array indexOfObjectWithOptions:NSEnumerationReverse passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
        if (idx < fromIndex) *stop = YES;
        return [obj isEqual:item];
    }];