What does “&error” mean in Objective-C? [duplicate]

故事扮演 提交于 2019-12-22 10:44:31

问题


Possible Duplicate:
why is “error:&error” used here (objective-c)

AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device
                                                                    error:&error];

What does the & symbol mean in the above code?


回答1:


It's the address-of operator; it produces a pointer pointing to the referent. In this case, error is an NSError *; AVCaptureDeviceInput deviceInputWithDevice:error: takes an address to it and may modify error through that pointer to indicate the error that occurred.




回答2:


error is a pointer to an error object. &error is a pointer to a pointer to an error object. If you pass a method a pointer to your pointer to an error and then an error occurs, the method can allocate an error object and set your error pointer to point to it.




回答3:


The & symbol is used to pass the address of the variable that is prefixed. It is also called pass by reference as opposed to pass by value. So &error means the address of error. Since error is defined as a pointer, then &error is the address of the pointer to the actual store of error.

The method you call may have the parameter defined as **error, thus forcing you to pass a pointer to the pointer, or reference to the pointer.

If a method uses *error as the parameter, the method can change the value pointed to by the parameter. This value can be referenced by the caller when the method returns control. However, when the method uses **error as the parameter, the method can also change the pointer itself, making it point to another location. This means that the caller's error variable will hence contain a new pointer.

Here is an example

    -(void)changePointerOfString:(NSString **)strVal {
        *strVal = @"New Value";
    }

    -(void)caller {
        NSString *myStr = @"Old Value";      // myStr has value 'Old Value'
        [self changePointerOfString:&myStr]; // myStr has value 'New Value'
    }


来源:https://stackoverflow.com/questions/13061381/what-does-error-mean-in-objective-c

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