1赡突、緣起:
在排查一個(gè)古老的版本上的bug時(shí)前鹅,定位到一處詭異的代碼。
2衰伯、復(fù)現(xiàn):
a)
NSString *contentType = nil;
NSRange range = [contentType rangeOfString:@"ssx:="];
if(range.location != NSNotFound) {
NSLog(@"====aaa");
}
//(NSRange) range = location=0, length=0
b)
NSString *contentType = @":\u4809";
NSRange range = [contentType rangeOfString:@":"];
if(range.location != NSNotFound) {
NSLog(@"====aaa");
}
c)
NSString *contentType = @"asad";
NSRange range = [contentType rangeOfString:@"ssx:="];
if(range.location != NSNotFound) {
NSLog(@"====aaa");
}
//(NSRange) range = location=9223372036854775807, length=0
d)
NSString *contentType = @"xasd";
NSRange range = [contentType rangeOfString:@""];
if(range.location != NSNotFound) {
NSLog(@"====aaa");
}
//(NSRange) range = location=9223372036854775807, length=0
3箱叁、官宣:
Return Value
An NSRange structure giving the location and length in the receiver of the first occurrence of searchString. Returns {NSNotFound, 0} if searchString is not found or is empty ("").
官方文檔指出:當(dāng)搜索的字符串沒(méi)有找到或者搜索的字符循環(huán)是空("",這里不要理解成" "后者是空格)時(shí)墅垮,會(huì)返回{NSNotFound,0}。
這里有一點(diǎn)需要重點(diǎn)提的是:如果NSRange range = [targetString rangeOfString:@"xxxxx"];
中targetString是nil時(shí)耕漱。range的值是{0,0}也就是初始化的默認(rèn)值算色。
上面提到的第二點(diǎn)絕對(duì)是一個(gè)陷阱,有很多代碼都包含了這個(gè)風(fēng)險(xiǎn)螟够。ex:
NSString *contentType = allResponseHeader[@"Content_type"];
if([contentType rangeOfString:@"ssx:="].location != NSNotFound) {//這個(gè)使用包含風(fēng)險(xiǎn)
//do something
}
這段代碼本意是要判斷conten_type如果包含了“ssx:=”字符串時(shí)灾梦,在執(zhí)行下面的操作,但是沒(méi)有考慮當(dāng)content_type為nil時(shí)妓笙,這個(gè)判斷是成立的若河,因?yàn)檫@時(shí)返回的NSRange是{0,0} !D萧福!這種用法都是照搬了網(wǎng)上的代碼,無(wú)腦使用辈赋,千萬(wàn)要注意v耆獭!钥屈!