个人而言,我真的很讨厌
NSNotFound
,但我理解它的必要性。但有些人可能不了解与
NSNotFound
进行比较的复杂性。例如,这段代码:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if([string rangeOfString:otherString].location != NSNotFound)
return YES;
else
return NO;
}
有问题的英文原句为:
has its problems:
1) Obviously if otherString = nil
this code will crash. a simple test would be:
其中
otherString = nil
表示代码中的一个变量等于空值(nil),如果这种情况发生,代码将会崩溃。可以通过简单的测试来验证。
NSLog(@"does string contain string - %@", [self doesString:@"hey" containString:nil] ? @"YES": @"NO");
结果是 !!崩溃!!
2)对于新接触Objective-C的人来说,不太明显的是当string = nil
时,相同的代码将不会崩溃。例如,以下代码:
NSLog(@"does string contain string - %@", [self doesString:nil containString:@"hey"] ? @"YES": @"NO");
这段代码:
NSLog(@"does string contain string - %@", [self doesString:nil containString:nil] ? @"YES": @"NO");
将会导致两者都。
does string contains string - YES
这段文字的英译中文如下:
这显然不是你想要的。
因此,我认为更好的解决方案是利用rangeOfString返回0的长度,因此更可靠的代码应该是这样的:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
if(otherString && [string rangeOfString:otherString].length)
return YES;
else
return NO;
}
或者简单地说:
- (BOOL)doesString:(NSString*)string containString:(NSString*)otherString {
return (otherString && [string rangeOfString:otherString].length);
}
这句话的意思是:“对于情况1和2,它将返回...”。
does string contains string - NO
那是我的两分钱 ;-)
请查看我的
Gist获取更多有用的代码。
if ([string rangeOfString:@"hello"] == 0) {...}
会导致 NSRange 和 int 类型不匹配的错误。要解决这个问题,您应该将该行更改为以下内容:if ([string rangeOfString:@"hello"].length == 0) {...}
。 - Neeku