NSString & NSMutableString

Immutable strings

 

//  Setup  two  variables  to  point  to  the  same  string 
NSString * str1 = @"Hello World"; 
NSString * str2 = str1; 

//  "Replace"  the  second  string 
str2 = @"Hello ikilimnik"; 

//  And  list  their  current  values 
NSLog(@"str1 = %@, str2 = %@", str1, str2); 

 

output:str1 = Hello World, str2 = Hello ikilimnik 



Mutable strings 

//  Setup  two  variables  to  point  to  the  same  string 
NSMutableString * str1 = [NSMutableString stringWithString:@"Hello World"]; 
NSMutableString * str2 = str1; 

//  "Replace"  the  second  string 
[str2 setString:@"Hello ikilimnik"]; 

//  And  list  their  current  values 
NSLog(@"str1 = %@, str2 = %@", str1, str2); 

 

output:str1 = Hello ikilimnik, str2 = Hello ikilimnik 

 

注意,当你使用不可变的NSString class时,替换旧的字符串的唯一方式就是创建一个新的字符串然后更新你的变量“str2”

来指向这个新的字符串。这个操作不会影响“str1”所指向的内容,因此它将继续指向初始的字符串。

 

在NSMutableString的例子里,我们没有创建第二个字符串,而是通过改变已经存在的可变字符串“str2”的内容来代替。

由于str1和str2两个变量都仍然指向同一个字符串对象,从nslog中可以看到它们值都将会被更新。

 

理解指针变量和它实际指向对象的不同是非常重要的。一个NSString对象是不可变的,但是这并不阻止你改变指向这个不

可变对象的指针的值。

 

"NSString *"这个数据类型代表一个NSString对象的指针,不是NSString对象本身。

"NSMutableString *"这个数据类型则是代表"NSMutableString"对象本身,这两者是有区别的。

 

这也是有的时候我们使用NSMutableString类型字符串时,要使用copy的原因,因为可能不想改变新的字符串时影响到旧的字符串的值。


From: http://blog.csdn.net/bl1988530/article/details/6548095

发布了28 篇原创文章 · 获赞 13 · 访问量 95万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章