Objective-C中的字符串比较

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

相关文章
相关标签/搜索