自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

Objective-C中的字符串比較

移動(dòng)開(kāi)發(fā) iOS
還是對(duì)Objective-C欠熟悉,一個(gè)很簡(jiǎn)單的字符串比較,想當(dāng)然的按照C/C++的方式來(lái)處理,結(jié)果debug了好半天得不到正確的結(jié)果,Google之后才想起來(lái)原來(lái)是這么回事。

Objective-C中,NSString的==操作符比較的是字符串地址,不是字符串內(nèi)容,如果需要比較內(nèi)容則需要使用isEqualToString:方法。具體的介紹可以看這里. 但是Xcode會(huì)對(duì)部分字符串做優(yōu)化,相同的字符串會(huì)使用同一份拷貝,所以有時(shí)候也會(huì)出現(xiàn)意想不到的“正確”結(jié)果,比如:

  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"); 

這段代碼會(huì)打印出 str1 equals str2,但是這樣就不會(huì):

  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"); 

另外,正確的字符串內(nèi)容比較方法為:

  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

責(zé)任編輯:佚名 來(lái)源: 白云哥博客
相關(guān)推薦

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-10 18:07:29

Objective-C反射

2011-08-04 10:57:33

Objective-C C語(yǔ)言 BOOL

2013-03-26 10:35:47

Objective-C單例實(shí)現(xiàn)

2011-07-20 13:34:37

Objective-C self.

2013-03-27 12:54:00

iOS開(kāi)發(fā)Objective-C

2013-06-20 10:40:32

Objective-C實(shí)現(xiàn)截圖

2011-05-11 11:20:26

Objective-C

2011-05-11 15:58:34

Objective-C

2015-07-08 10:51:27

Objective-CRuntime

2011-07-27 16:18:42

Objective-c 協(xié)議

2011-08-15 17:06:01

Objective-CNSLog

2011-07-08 18:44:09

Objective-C Self Super

2009-02-24 15:39:27

字符串比較函數(shù)函數(shù)

2011-08-04 14:58:37

Objective-C Cocoa NSString

2011-08-02 13:16:36

Objective-C 語(yǔ)法 函數(shù)

2011-05-11 13:54:08

Objective-C

2011-05-11 15:45:50

內(nèi)存管理Objective-C
點(diǎn)贊
收藏

51CTO技術(shù)棧公眾號(hào)