5

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.

4

1 回答 1

10

传递双指针允许函数交换您传入的对象。一个很好的例子是所有将双指针传递给 NSError 的许多 Cocoa API。看看这个:

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

在这种情况下,我们没有传递一个实际的错误实例,但是由于我们传递了一个指向我们的错误的指针,这允许他们在这个方法中创建一个 NSError 实例,并且在退出后,我们将指向那个新实例。

于 2013-10-11T17:05:00.223 回答