如何对一个字符串有多个引用

发布于 2024-12-22 18:56:41 字数 706 浏览 2 评论 0原文

请检查下面的代码,我在其中为数组创建多个引用

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

貪欢 2024-12-29 18:56:41

一切都很正常。 With :

str1 = @"Hello";

str1 不再指向您在上面两行分配的内存。 str2 没有改变,仍然指向那个内存位置。

您给出的示例对于数组和字符串来说看起来并不相同。第一种方法是将对象添加到一个数组中,但不更改任何指针的值。

在第二步中,您将修改对对象的引用

第二个例子应该写成:

NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
[str1 appendString:@"foo"];

NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);

输出:

Str1:foo
Str2:foo

给定同一个可变字符串(一个内存位置)上的两个引用,并使用NSMutableString的方法,两个引用都将被修改。

Everything is quite normal. With :

str1 = @"Hello";

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 :

NSMutableString *str1 = [[NSMutableString alloc] init];
NSMutableString *str2 = str1;
[str1 appendString:@"foo"];

NSLog (@"Str1 : %@", str1);
NSLog (@"Str2 : %@", str2);

Output :

Str1 : foo
Str2 : foo

Given two references on the same mutable string (one memory place), and using NSMutableString's method, both references will be modified.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文