Objective-C中,NSString的==操做符比較的是字符串地址,不是字符串內容,若是須要比較內容則須要使用isEqualToString:方法。具體的介紹能夠看這裏:http://iphonedevelopertips.com/cocoa/compare-nsstrings-objects.html 可是Xcode會對部分字符串作優化,相同的字符串會使用同一份拷貝,因此有時候也會出現意想不到的「正確」結果,好比:html
1objective-c 2iphone 3優化 4this 5spa 6.net 7code 8orm |
NSString *str1 = @"Homebrew";htm NSString *str2 = @"Homebrew";
// This compares the addresses of the string if (str1 == str2) NSLog (@"str1 equals str2"); else NSLog (@"str1 does not equal str2"); |
這段代碼會打印出 str1 equals str2,可是這樣就不會:
1 2 3 4 5 6 7 8 9 10 |
// Create a C string char *cStr = "Homebrew"; NSString *str3 = [NSString stringWithUTF8String:cStr]; NSString *str4 = @"Homebrew";
// Wrong - this compares the address of the string if (str3 == str4) NSLog (@"str3 equals str4"); else NSLog (@"str3 does not equal str4"); |
另外,正確的字符串內容比較方法爲:
1 2 3 4 5 6 7 8 |
char *cStr = "Homebrew"; NSString *str3 = [NSString stringWithUTF8String:cStr]; NSString *str4 = @"Homebrew";
if ([str3 isEqualToString:str4]) NSLog (@"str3 equals str4"); else NSLog (@"str3 does not equal str4"); |
來源:http://all-ipad.net/string-compare-in-objective-c/?utm_source=rss&utm_medium=rss&utm_campaign=string-compare-in-objective-c