借助示例,目标C中的NSString和NSMutableString之间的实际区别是什么? [英] what is actual difference between NSString and NSMutableString in objective C with the help of example?
问题描述
Objective-C中NSString和NSMutable String之间的实际区别是什么? 我已经搜索了很多,但没有得到任何答案..我了解NSString是Immutable对象,而NSMutableString是Mutable对象,但是我想借助示例来了解它们之间的区别..请帮助我..
what is actual difference between NSString and NSMutable String in Objective-C? I have searched a lot but not getting any answer..I understand that NSString is Immutable object and NSMutableString is Mutable object but I want to understand the difference between them with the help of an example..Please help me..
现在问题已经解决了..
now question has solved..
推荐答案
不可变的字符串.....
Immutable String.....
NSString *str1 = @"Hello Testing";
NSString *str2 = str1;
替换第二个字符串
str2 = @"Hello hehehe";
并列出其当前值
NSLog(@"str1 = %@, str2 = %@", str1, str2);
//logs as below
//str1 = Hello Testing, str2 = Hello hehehe
可变字符串
设置两个变量以指向相同的字符串
Setup two variables to point to the same string
NSMutableString * str1 = [NSMutableString stringWithString:@"Hello Testing"];
NSMutableString * str2 = str1;
替换第二个字符串
[str2 setString:@"Hello ikilimnik"];
//并列出其当前值
NSLog(@"str1 = %@, str2 = %@", str1, str2);
//logs as below
//str1 = Hello ikilimnik, str2 = Hello ikilimnik
当使用不可变字符串类时,请注意,replace
字符串的唯一方法是创建新字符串并更新变量str2
指向它.
Notice when you use the immutable string class that the only way to replace
a string is to create a new string and update your variable str2
to point to it.
但这不会影响str1指向的内容,因此它仍将引用原始字符串.
This however doesn't affect what str1 is pointing to, so it will still reference the original string.
在NSMutableString
示例中,我们没有创建第二个字符串,而是更改了
现有的Hello Testing
字符串.由于两个变量继续指向同一字符串对象,因此它们都将在对NSLog
的调用中报告新值.
In the NSMutableString
example, we don't create a second string, but instead alter the contents of
the existing Hello Testing
string. Since both variables continue to point to the same string object, they will both report the new value in the call to NSLog
.
区分指针变量和它指向的实际对象很重要.
NSString
对象是不可变的,但这不会阻止您更改指向字符串的变量的值.
It is important to differentiate between a pointer variable and the actual object it points to.
A NSString
object is immutable, but that doesn't stop you from changing the value of a variable which points to a string.
这篇关于借助示例,目标C中的NSString和NSMutableString之间的实际区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!