截取<a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>
中的微博 weibo.com
这一段字符串。代码如下:
- (void)setSource:(NSString *)source
{
//字符串示例 <a href="http://weibo.com/" rel="nofollow">微博 weibo.com</a>
//范围
NSRange range = NSMakeRange(0, 0);
//获取要截取的字符串的起始字符的位置
range.location = [source rangeOfString:@">"].location + 1;
//反向检索NSBackwardsSearch
range.length = [source rangeOfString:@"<" options:NSBackwardsSearch].location - range.location;
_source = [source substringWithRange:range];
}
得出的结构符合预期,但是控制台里探出两条内容一样的警告:
2015-08-18 11:16:57.402 weibo[2568:69911] -[__NSCFConstantString substringWithRange:]: Range {9223372036854775808, 18446744073709551615} out of bounds; string length 0
2015-08-18 11:16:57.403 weibo[2568:69911] -[__NSCFConstantString substringWithRange:]: Range {9223372036854775808, 18446744073709551615} out of bounds; string length 0
我看了几遍,发现如果将_source = [source substringWithRange:range];
这一行注释掉,就没有警告了,但是我觉得range没有求错啊,奇了怪了。
I didn’t reproduce this... I used your code:
Console output
微博 weibo.com
, no warning...Many people have encountered this problem. . . .
Not surprising, the reason is that the parameters you pass in sometimes do not have "<" and ">"
If you don’t believe it, change it to
I tried the above method, but there is still a warning: [__NSCFConstantString substringWithRange:]: Range {9223372036854775808, 18446744073709551615} out of bounds; string length 0
Finally, I do this,
The problem is that your NSRange is initialized incorrectly. Use
NSRange range = NSMakeRange(0, 0);
才是正确的初始化方法。NSRange在初始化的时候如果用NSRange range;
,没有指定range的初值,就会有时候出现这个错误——Range {9223372036854775808, 18446744073709551615} out of bounds; string length 0
This error is that the x and y values in range{x,y} are out of range, because you did not initialize it to {0, 0}, and sometimes it will be initialized to The two numbers in the error. And this error is not fixed, but occurs occasionally. The two numbers 9223372036854775808 and 18446744073709551615 both overflow the memory when converted to 64 bits. When you initialize, the memory has already overflowed. How can you find it?
The most important thing is - this error occurs randomly! For example, if I use it fine today, it may report an error tomorrow. This can be said to be a bug in the Objective-C language itself.
I have also encountered this problem. It may be because the loaded data is real-time data from the Internet. If there are exceptions, it will cause occasional crashes. Try adding a judgment in front of it
if ([source isEqualToString:@""]) return;