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?
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
.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With