NSRange: range.location != NSNotFound vs. range.length > 0

MikeS picture MikeS · Oct 10, 2012 · Viewed 20.4k times · Source

I'm going through some older code in one of my apps and fixing up the code in areas that could be potentially problematic.

I'm seeing a lot of old code using...

NSRange range = //determine range here....
if(range.length > 0)
{
    //do stuff
}

Is that code "fine", or should I change it to this?

NSRange range = //determine range here....
if(range.location != NSNotFound)
{
    //do stuff
}

Are these two methods identical, essentially, or not?

Answer

rob mayoff picture rob mayoff · Oct 10, 2012

The two checks are not always identical. It depends on how the range was generated. Example:

NSRegularExpression *re = [NSRegularExpression
    regularExpressionWithPattern:@"(?= )" options:0 error:NULL];
NSTextCheckingResult *result = [re firstMatchInString:@"hello world"
    options:0 range:NSMakeRange(0, 11)];
NSLog(@"range = %@", NSStringFromRange(result.range));

The range's length is 0, but its location is 5, not NSNotFound.