NSRange 的问题
我在使用 NSRange 时遇到问题。这是我的代码:
NSRange range = [[[NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:cookie]]] objectForKey:@"Cookie"] rangeOfString:@"x"];
NSLog(@"%f", range.length);
if (range.length >= 1) {
NSLog(@"Do Something");
} else {
NSLog(@"AUTHING");
}
控制台输出:
0.000000
Do something
然后第二次运行代码:
0.000000
AUTHING
到底发生了什么? NSNotFound 我认为它不起作用,而且我不是唯一发现这个问题的人,所以使用它不是一个解决方案。
感谢您的任何帮助。
干杯
编辑:我尝试使用 NSLog(@"%d", range.length) 但它第一次运行时给出了错误的输出,第二次运行时它给出了正确的输出。我尝试使用 NSNotFound 认为奇怪的输出是由于它是 NSNotFound 但它没有触发
I'm having a problem with NSRange. Here is my code:
NSRange range = [[[NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:[NSURL URLWithString:cookie]]] objectForKey:@"Cookie"] rangeOfString:@"x"];
NSLog(@"%f", range.length);
if (range.length >= 1) {
NSLog(@"Do Something");
} else {
NSLog(@"AUTHING");
}
Console output:
0.000000
Do something
And then the second time I run through the code:
0.000000
AUTHING
What the hell is going on? NSNotFound I think it was does not work and I'm not the only person finding this problem so using it is not a solution.
Thanks for any help.
Cheers
Edit: I tried using NSLog(@"%d", range.length) but it gives incorrect output the first time it runs through, the second time it runs through it is correct. I've tried using NSNotFound thinking that the strange output is due to it being NSNotFound but it didn't trigger
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果你想查看是否使用
-[NSString rangeOfString:]
找到了字符串,你需要查看是否 NSRange.location == NSNotFound:If you want to see if the string was found using
-[NSString rangeOfString:]
, you need to see if NSRange.location == NSNotFound:作为一般评论,如果您拆分嵌套方法调用并执行快速 NSLog 来查看发生了什么,那么调试会容易得多。 (我不太擅长遵守这一点,所以这并不是批评)。
我首先注意到的一件事是使用“%f”来显示长度,尝试使用%i(整数),您应该能够获得正确的长度。 %f 将始终显示 0.00000。
你用什么网址?鉴于您正在从标题中提取数据,字符串“x”可能会也可能不会出现在该字段中。我建议 NSLog-ing 从字典中取出的 NSString* 对象并检查发生了什么。例如:NSString *cookie = @"http://www.google.com/";
据我所知,代码似乎只是检测字符串“x”的索引,这是预期的结果吗?
As a general comment, debugging is much easier if you split up the nested method calls and do a quick NSLog to see what's going on. (i'm not that good at adhering to that so it's not meant as criticism).
One thing i first noted was the use of "%f" to display the length, try using %i (integer) and you should be able to get the correct length. %f will always display 0.00000.
what url are you using? given that you are pulling the data from the headers, the string "x" may or may not be present in the field. i would suggest NSLog-ing the NSString* object that you pull out of the dictionary and checking to see what's going on. E.g.:NSString *cookie = @"http://www.google.com/";
It seems like the code just detects the index of the string "x" from what I can tell, is this the intended result?