Objective-C中的字符串比较

移动开发 iOS
还是对Objective-C欠熟悉,一个很简单的字符串比较,想当然的按照C/C++的方式来处理,结果debug了好半天得不到正确的结果,Google之后才想起来原来是这么回事。

Objective-C中,NSString的==操作符比较的是字符串地址,不是字符串内容,如果需要比较内容则需要使用isEqualToString:方法。具体的介绍可以看这里. 但是Xcode会对部分字符串做优化,相同的字符串会使用同一份拷贝,所以有时候也会出现意想不到的“正确”结果,比如:

  1. NSString *str1 = @"Homebrew"
  2. NSString *str2 = @"Homebrew"
  3.  
  4. // This compares the addresses of the string 
  5. if (str1 == str2) 
  6. NSLog (@"str1 equals str2"); 
  7. else 
  8. NSLog (@"str1 does not equal str2"); 

这段代码会打印出 str1 equals str2,但是这样就不会:

  1. // Create a C string 
  2. char *cStr = "Homebrew"
  3. NSString *str3 = [NSString stringWithUTF8String:cStr]; 
  4. NSString *str4 = @"Homebrew"
  5.  
  6. // Wrong - this compares the address of the string 
  7. if (str3 == str4) 
  8.   NSLog (@"str3 equals str4"); 
  9. else 
  10.   NSLog (@"str3 does not equal str4"); 

另外,正确的字符串内容比较方法为:

  1. 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

责任编辑:佚名 来源: 白云哥博客
相关推荐

2011-08-04 17:13:48

Objective-C 字符串

2011-08-10 11:08:32

Objective-C字符串NSString

2011-08-15 17:47:13

Objective-CisMemberOfC

2011-08-04 10:57:33

Objective-C C语言 BOOL

2013-03-26 10:35:47

Objective-C单例实现

2009-02-24 15:39:27

字符串比较函数函数

2011-08-10 18:07:29

Objective-C反射

2015-07-08 10:51:27

Objective-CRuntime

2011-07-20 13:34:37

Objective-C self.

2013-03-27 12:54:00

iOS开发Objective-C

2011-05-11 11:20:26

Objective-C

2011-05-11 15:58:34

Objective-C

2013-06-20 10:40:32

Objective-C实现截图

2011-07-08 18:44:09

Objective-C Self Super

2011-08-15 17:06:01

Objective-CNSLog

2011-07-27 16:18:42

Objective-c 协议

2013-04-11 13:41:30

Objective-CiOS编程

2014-11-25 10:18:17

Objective-C

2014-07-29 09:44:35

2011-08-04 14:58:37

Objective-C Cocoa NSString
点赞
收藏

51CTO技术栈公众号