Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C pass by reference vs pass by pointer. What's the difference? And why do we need it at all? [duplicate]

In Objective-C I saw two common patterns for passing objects to functions. Basically all objects to functions are passed by reference like this: -(void) someFunc:(UIImage*)image; this is pass by reference, isn't it?

But then what is this: -(void) someFunc2:(UIImage**)image?? Is it also passing by reference? Or passing by pointer to pointer? Or what? I don't understand what is an actual difference (but I saw this code a lot). And the main question: why do we need this pointer to pointer passing : -(void) someFunc2:(UIImage**)image? Thanks.

like image 528
MainstreamDeveloper00 Avatar asked Oct 11 '13 16:10

MainstreamDeveloper00


People also ask

Are pointers passed by reference or value in C?

Even though C always uses 'pass by value', it is possible simulate passing by reference by using dereferenced pointers as arguments in the function definition, and passing in the 'address of' operator & on the variables when calling the function.

What is pass by reference and pass by value?

Pass by Value: The method parameter values are copied to another variable and then the copied object is passed, that's why it's called pass by value. Pass by Reference: An alias or reference to the actual parameter is passed to the method, that's why it's called pass by reference.

What does pass by reference do?

Pass by reference (also called pass by address) means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function so that a copy of the address of the actual parameter is made in memory, i.e. the caller and the callee use the same variable for the parameter.

Is passing by reference faster?

What is surprising is that passing a complex object by reference is almost 40% faster than passing by value. Only ints and smaller objects should be passed by value, because it's cheaper to copy them than to take the dereferencing hit within the function.


1 Answers

Passing a double pointer allows the function to swap out the object you pass in. A good example is all of the many Cocoa APIs that pass a double pointer to an NSError. Take a look at this:

NSError *error = nil;
Result *result = [self someMethodWithPossibleError:&error];
if (![result isValid]) {
    //handle the error
    NSLog(@"Error occurred: %@", error);
}

In this case, we aren't passing an actual error instance, however since we are passing a pointer to our error, this allows them to create an NSError instance in this method, and after exiting, we will be pointing at that new instance.

like image 134
Lance Avatar answered Sep 29 '22 20:09

Lance