문제

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?

도움이 되었습니까?

해결책

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];
}];
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top