按值传递与按引用传递 [英] Pass by value vs Pass by reference

查看:65
本文介绍了按值传递与按引用传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

过去几天我一直在研究一些基础知识,但我意识到我从来没有真正理解为什么 NSString/NSMutableString 的传递引用不起作用.

I have been looking into some basics over the last couple days and I realized that i never truly understood why pass-by-reference for NSString/NSMutableString did not work.

- (void)testing{    

NSMutableString *abc = [NSMutableString stringWithString:@"ABC"];
[self testing:abc];
NSLog(@"%@",abc); // STILL ABC
}


-(void)testing:(NSMutableString *)str {
str = [NSMutableString stringWithString:@"HELP"];
}

我该怎么做?我希望我的测试方法能够从 main 方法操作 String.我一直在将它与可变数组、字典等一起使用,并且工作正常.感觉很奇怪,我从来没有意识到这是如何与字符串一起工作的.

How do i go about this? I want my testing method to be able to manipulate the String from the main method. I have been using this with Mutable Arrays, dictionary etc and works fine. Feels strange that I never realized how this works with Strings.

但是这个值在这样的地方被改变了,它是对第一个字符串的引用

But the value gets changed in something like this which is a reference to the first string

NSMutableString *string1;
NSMutableString *string2;

string1 = [NSMutableString stringWithString: @"ABC"];
string2 = string1;

[string2 appendString: @" HELP"];

NSLog (@"string1 = %@", string1); // ABC HELP
NSLog (@"string2 = %@", string2); // ABC HELP

推荐答案

和 Java 一样,Objective-C 也只有按值传递和赋值.也和 Java 一样,对象总是在指针后面(你永远不会把对象本身放到一个变量中).

Like Java, Objective-C has only passing and assigning by value. Also like Java, objects are always behind pointers (you never put the object itself into a variable).

当您分配或传递对象指针时,该指针将被复制并指向与原始指针相同的对象.这意味着,如果对象是可变的(即它有一些改变其内容的方法),那么您可以通过一个指针改变它并通过另一个指针查看效果.变异总是通过调用一个方法来实现,或者直接赋值给一个字段.

When you assign or pass an object pointer, the pointer is copied and points to the same object as the original pointer. That means, if the object is mutable (i.e. it has some method that mutates its contents), then you can mutate it through one pointer and see the effects through the other one. Mutation is always achieved by calling a method, or assigning to a field directly.

-(void)testing:(NSMutableString *)str {
  [str setString:@"HELP"];
}

赋值给一个指针永远不会改变它指向的对象;相反,它使指针指向另一个对象.

Assigning to a pointer never mutates the object it points to; rather, it makes the pointer point to another object.

这篇关于按值传递与按引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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