开发者

How to check if [request responseString] is equal to some other string?

开发者 https://www.devze.com 2023-04-02 14:41 出处:网络
For example [request responseString]\'s value sent by my servlet to my iphone application is\"myinfo\". In my iphone application, I made a string like thi开发者_如何学Gos:

For example [request responseString]'s value sent by my servlet to my iphone application is "myinfo". In my iphone application, I made a string like thi开发者_如何学Gos:

 NSString *str = @"myinfo";

then i have if else

 if([responseString isEqualToString:str]){
    NSLog(@"condition true");

}else{
        NSLog(@"condition false");
}

in console its always showing "condition false". Whats the problem? Isn't isEqualToString is write method to check if strings are equal or not? Thanks in advance.


Howwever much you think your two strings are completely equal, they are not. Believe me, if -isEqualToString: did not return YES for two equal strings, somebody would have noticed in the 20 odd years it has been part of the Cocoa API.

I suspect that one of your two strings contains some non printing characters. You might have a line feed or a space or a tab in it. Another possibility (one that I came across recently) is that, for certain character set encodings, you can create an NSString with a nul character in it. If it's at the end, it won't show up. Try logging the lengths of the two strings, or converting them to NSData objects using the UTF16 encoding and logging them.


The NSString method isEqualToString is the correct thing to use here. You can do a sanity check by adding a log to your method:

NSLog(@"responseString = %@",responseString);
NSLog(@"str = %@",str);

if([responseString isEqualToString:str]){
    NSLog(@"condition true");

}else{
    NSLog(@"condition false");
}

Remember that NSStrings are Case Sensitive, so the two strings must appear exactly the same.


Since you said you're using connectios, sometimes the data retrieved by web is weird, you should first encode the data in a string and then NSLog it to see if it has special characters.

NSString *response = [[NSString alloc] initWithData:dataRetrieved encoding:NSUTF8StringEncoding];

Then you can make sure if your [request responseString] is not getting special chars.


The better way to compare strings in ios:

NSString *responseString = <your string>;
NSString *string2 = <your string>;

if ([responseString caseInsensitiveCompare:string2] == NSOrderedSame) {
    //strings are same
} else {
    //strings are not same
}
0

精彩评论

暂无评论...
验证码 换一张
取 消