Pass by value vs Pass by reference

浪尽此生 提交于 2019-12-08 09:56:40

问题


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"];
}

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

回答1:


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.




回答2:


I cannot in good conscious let this wrong answer linger on the internet.

Pass by reference in objective c is POSSIBLE; which is why it is better than Java.

Here's how:

- (void)testing
{    
    NSMutableString *abc = [NSMutableString stringWithString:@"ABC"];
    [self testingHelper:&abc];
    NSLog(@"%@", abc); // NOW HELP
}

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


来源:https://stackoverflow.com/questions/10512636/pass-by-value-vs-pass-by-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!