Comparing a string from the web
hey all, i'm trying to read a file on the web that says "this is a test" and i wanna compare it... so here's what i got:
NSError *error;
NSURL *theURL = [NSURL URLWithString:@"http://mysite.com/test.asp"];
NSString *test = [NSString stringWithContentsOfURL:theURL encoding:NSASCIIStringEncoding error:&error];
NSLog(@"%@",test); //prints the results.. .does work
开发者_如何转开发if(test == "this is a test"){
NSLog(@"File read");
} else {
NSLog(@"Bad file");
}
What am i doing wrong here? I always get "Bad file" but i know it's pulling in the text. Thanks all
damien
You need to check for nil as well & use isEqualToString function for comparison.
if(test != nil){
if([test isEqualToString:@"this is a test"]) {
// equal
}
else{
// not equal
}
}
else{
NSLog(@"Bad file");
}
If you use ==
, you'll be comparing two pointers. Use isEqual:
like so:
if([test isEqual: @"this is a test"]) {
// equal
}else{
// not equal
}
Other than the 2 answer you can also use.
– caseInsensitiveCompare:
– localizedCaseInsensitiveCompare:
– compare:
– localizedCompare:
– compare:options:
– compare:options:range:
– compare:options:range:locale:
– localizedStandardCompare:
精彩评论