Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 300
MikeS Avatar asked Oct 10 '12 20:10

MikeS


2 Answers

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.

like image 93
rob mayoff Avatar answered Oct 30 '22 22:10

rob mayoff


The answer depends on the function/method you are using. NSRange is just a struct so you need to read the documentation for the function/method you are calling.

Examples:

NSRangeFromString
Returns a range from a textual representation.

... If aString does not contain any integers, this function returns an NSRange struct whose location and length values are both 0.

In this case checking for NSNotFound would not work.


-[NSString rangeOfString:]

... Returns {NSNotFound, 0} if aString is not found or is empty (@"").

Here it is documented that location will be NSNotFound and the length will be 0 so either of the checks would work, however, I would recommend checking the location against NSNotFound.

like image 43
Joe Avatar answered Oct 30 '22 23:10

Joe