如何对一个字符串有多个引用
请检查下面的代码,我在其中为数组创建多个引用
NSMutableArray *array1 = [[NSMutableArray alloc] init];
NSMutableArray *array2 = array1;
[array1 addObject:@"One"];
[array1 addObject:@"Two"];
NSLog (@"Array1 %@",array1);
NSLog (@"Array2 %@",array2);
控制台输出为
数组1( 一, 两个)数组2( 一, 两个)
Array1和Array2都引用相同的地址
同样,我尝试了NSMutableString,但没有成功
NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
str1 = @"Hello";
NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);
控制台输出为 Str1 Hello Str2 (null)
有没有办法引用 string ?
Please check the below code, where I am creating multiple reference for an array
NSMutableArray *array1 = [[NSMutableArray alloc] init];
NSMutableArray *array2 = array1;
[array1 addObject:@"One"];
[array1 addObject:@"Two"];
NSLog (@"Array1 %@",array1);
NSLog (@"Array2 %@",array2);
Console output is
Array1 (
One,
Two ) Array2 (
One,
Two )
Both Array1 and Array2 reference to same address
Like wise I tried for NSMutableString, I didn't work out
NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
str1 = @"Hello";
NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);
Console Output is Str1 Hello Str2 (null)
Is there any way to have reference to string ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一切都很正常。 With :
str1
不再指向您在上面两行分配的内存。str2
没有改变,仍然指向那个内存位置。您给出的示例对于数组和字符串来说看起来并不相同。第一种方法是将对象添加到一个数组中,但不更改任何指针的值。
在第二步中,您将修改对对象的引用。
第二个例子应该写成:
输出:
给定同一个可变字符串(一个内存位置)上的两个引用,并使用
NSMutableString
的方法,两个引用都将被修改。Everything is quite normal. With :
str1
doesn't point to the memory you allocated two lines above anymore.str2
didn't change and still point to that memory place.The example you gave doesn't looks the same for arrays and string. In the first you add objects to one array, but don't change the value of any pointer.
In the second you are modifiying the reference to an object.
The second example, should be written as something like :
Output :
Given two references on the same mutable string (one memory place), and using
NSMutableString
's method, both references will be modified.