Search code examples
objective-cindexingnsrange

Objective-C Extract index of a range returned by rangeOfString:


How to extract an NSUInteger index from

NSRange range = [string rangeOfString: substring]

so I can write this index in [array objectAtIndex:index]?


Solution

  • // make sure that the substring was actually found:
    NSRange result = [string rangeOfString:substring];
    
    if (result.location != NSNotFound)
    {
        // make sure that the index exists in the array
        if (result.location < [array count])
        {
            id someObj = [array objectAtIndex:result.location];
            // do something cool with someObj here
        }
    }