[英]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? 这两种方法基本上是否相同?
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
. 范围的长度为0,但其位置为5,而不是
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. NSRange
只是一个结构,因此您需要阅读您正在调用的函数/方法的文档。
Examples: 例子:
NSRangeFromString 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.
...如果aString不包含任何整数,则此函数返回NSRange结构,其位置和长度值均为0。
In this case checking for NSNotFound
would not work. 在这种情况下,检查
NSNotFound
将不起作用。
-[NSString rangeOfString:] - [NSString rangeOfString:]
... Returns {NSNotFound, 0} if aString is not found or is empty (@"").
...如果找不到aString或为空(@“”),则返回{NSNotFound,0}。
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
. 这里记录了位置将是
NSNotFound
, length
将为0,因此任何一个检查都可以,但是,我建议根据NSNotFound
检查位置。
NSNotFound is defined as "NSIntegerMax". NSNotFound定义为“NSIntegerMax”。 Even if they produce the same result your second display is far more readable and self documenting.
即使它们产生相同的结果,您的第二个显示器也更具可读性和自我记录性。 Maybe you shouldn't find them all and change them but just switch to that moving forward.
也许你不应该找到它们并改变它们,但只需转向前进即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.