NSString不可变允许更改其值? [英] NSString immutable allows to change its values?

查看:114
本文介绍了NSString不可变允许更改其值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码可以编译并运行,但是根据所有iPhone开发书籍和Apple文档,它不应该!有人可以向我解释不可变的NSString如何在设置后更改其值吗?我以为我必须使用NSMuttableString来更改同一字符串变量的上下文?我正在使用SDK 3.1.

The code below compiles and runs, BUT according to all iPhone development books and Apple documentation it shouldnt! Can someone please explain to me how come immutable NSString allows to change its values after it has been set? I thought I had to use NSMuttableString to change context of the same string variable? I am using SDK 3.1.

NSString *test =[[NSString alloc] initWithString:@"TEST"];
[test release];
test = @"TEST2";

推荐答案

下面的示例也许会加上Mark和Niels的回复,并有助于澄清问题.

Perhaps the following example will add upon the replies from Mark and Niels and help clarify things.

不变的字符串

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

可变字符串

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

请注意,当您使用不可变的NSString类时,替换"字符串的唯一方法是创建新字符串并更新变量"str2"以指向该字符串.但是,这不会影响"str1"指向的内容,因此仍将引用原始字符串.

Notice when you use the immutable NSString class that the only way to "replace" a string is to create a new string and update your variable "str2" to point to it. This however doesn't affect what "str1" is pointing to, so it will still reference the original string.

在NSMutableString示例中,我们没有创建第二个字符串,而是更改(变异)现有"Hello World"字符串的内容.由于两个变量继续指向同一字符串对象,因此它们都将在对NSLog的调用中报告新值.

In the NSMutableString example, we don't create a second string, but instead alter (mutate) the contents of the existing "Hello World" 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's 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.

数据类型"NSString *"是指向NSString对象而不是对象本身的指针.如果您在XCode调试器中的任意一个NSLog语句中设置了一个断点,则可能需要检查每个变量的原始值来阐明这一点.

The data type "NSString *" is a pointer to a NSString object, not the object itself. If you set a break point at either of the NSLog statements within the XCode debugger, you may like to check the raw value of each variable to clarify this.

这篇关于NSString不可变允许更改其值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆