2009年12月21日星期一

學習compare NSSTring Objects

在Objective-C和COCOA 如何比較兩個NSString 類型的字串是否相等呢?
第一個想到的是"==",但是這個不正確,應該是 isEqualToString

NSString *str1 = @"Homebrew";
NSString *str2 = @"Homebrew";

if(str1 == str2)
{
NSLog(@"str1 equals str2");
}else{
NSLog(@"Str1 does not equal str2");
}

NSLog(@"str1 address in memory : %p", str1);
NSLog(@"str2 address in memory : %p", str2);



char * cStr = "Homebrew";
NSString *str3 = [NSString stringWithUTF8String:cStr];
NSString *str4 = @"Homebrew";

if(str3 == str4)
{
NSLog(@"str3 equals to str4");
}
else{
NSLog(@"str3 does not equals to str4");
}

NSLog(@"str3 address in memory is %p", str3);
NSLog(@"str4 address in memory is %p", str4);


if([str3 isEqualToString: str4])
{
NSLog(@"str3 equals str4");
}else{
NSLog(@"str3 does not equal str4");
}


結果:
[Session started at 2009-12-22 09:58:59 +0800.]
2009-12-22 09:58:59.699 Movie_Player2[34747:10b] str1 equals str2
2009-12-22 09:58:59.710 Movie_Player2[34747:10b] str1 address in memory : 0x2030
2009-12-22 09:58:59.710 Movie_Player2[34747:10b] str2 address in memory : 0x2030
2009-12-22 09:58:59.711 Movie_Player2[34747:10b] str3 does not equals to str4
2009-12-22 09:58:59.711 Movie_Player2[34747:10b] str3 address in memory is 0x105bc0
2009-12-22 09:58:59.712 Movie_Player2[34747:10b] str4 address in memory is 0x2030
2009-12-22 09:58:59.713 Movie_Player2[34747:10b] str3 equals str4

The Debugger has exited with status 0.

參考解釋是:
The reason this works is that the complier can manage strings internally when you define them using the shortcut method(@"stringhere") and will store only one reference internally to duplicates.
You can verify that the strings refer to the same content by looking at the locations in memory where the variables are stored.

The Correct way to compare Strings
the right way to go about this is use the isEqualToString: method in the NSString class


ref:http://iphonedevelopertips.com/cocoa/compare-nsstrings-objects.html

没有评论:

发表评论