Problem with NSRange

Rudiger picture Rudiger · Nov 30, 2010 · Viewed 22.5k times · Source

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

Answer

Nick Forge picture Nick Forge · Nov 30, 2010

If you want to see if the string was found using -[NSString rangeOfString:], you need to see if NSRange.location == NSNotFound:

if (range.location != NSNotFound) {
    // String was found
else {
    // String not found
}