Question

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

Was it helpful?

Solution

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
}

OTHER TIPS

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/";

NSHTTPCookieStorage *store = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSURL *url = [NSURL URLWithString:cookie];
NSDictionary *header = [NSHTTPCookie requestHeaderFieldsWithCookies: [store cookiesForURL:url]];
NSString *cookieParameter = [header objectForKey:@"Cookie"];    

NSLog(@"Cookie param is %@", cookieParameter);

// Test range of "x"
NSRange range = [cookieParameter rangeOfString:@"x"];
NSLog(@"%f", range.length); // will print out 0.00000
NSLog(@"%i", range.length); // will print out correct length (always 1 for "x")
NSLog(@"%i", range.location); // will print out the location of the first instance of "x"
if (range.length >= 1) {
    NSLog(@"Do Something");
} else {
    NSLog(@"AUTHING");
}

It seems like the code just detects the index of the string "x" from what I can tell, is this the intended result?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top