什么是双星(例如 NSError **)? [英] What is double star (eg. NSError **)?
问题描述
所以,我看到了:
error:(NSError **)error
在苹果文档中.为什么是两星?有什么意义?
in the apple doc's. Why two stars? What is the significance?
推荐答案
双星"是指向指针的指针.所以NSError **
是一个指向NSError
类型的对象的指针.它基本上允许您从函数返回一个错误对象.您可以在函数中创建一个指向 NSError
对象的指针(称为 *myError
),然后执行以下操作:
A "double star" is a pointer to a pointer. So NSError **
is a pointer to a pointer to an object of type NSError
. It basically allows you to return an error object from the function. You can create a pointer to an NSError
object in your function (call it *myError
), and then do something like this:
*error = myError;
将该错误返回"给调用者.
to "return" that error to the caller.
回复下面发表的评论:
你不能简单地使用NSError *
,因为在C中,函数参数是按值传递的——也就是说,值被复制 传递给函数时.为了说明这一点,请考虑以下 C 代码片段:
You can't simply use an NSError *
because in C, function parameters are passed by value—that is, the values are copied when passed to a function. To illustrate, consider this snippet of C code:
void f(int x)
{
x = 4;
}
void g(void)
{
int y = 10;
f(y);
printf("%d
", y); // Will output "10"
}
f()
中 x
的重新赋值不会影响 f()
之外的参数值(在 g()
,例如)
The reassignment of x
in f()
does not affect the argument's value outside of f()
(in g()
, for example).
同样,当一个指针传入函数时,它的值被复制,重新赋值不会影响函数外的值.
Likewise, when a pointer is passed into a function, its value is copied, and re-assigning will not affect the value outside of the function.
void f(int *x)
{
x = 10;
}
void g(void)
{
int y = 10;
int *z = &y;
printf("%p
", z); // Will print the value of z, which is the address of y
f(z);
printf("%p
", z); // The value of z has not changed!
}
当然,我们知道我们可以很容易地改变 z
指向的值:
Of course, we know that we can change the value of what z
points to fairly easily:
void f(int *x)
{
*x = 20;
}
void g(void)
{
int y = 10;
int *z = &y;
printf("%d
", y); // Will print "10"
f(z);
printf("%d
", y); // Will print "20"
}
所以按理说,要改变 NSError *
指向的值,我们还必须传递一个指向该指针的指针.
So it stands to reason that, to change the value of what an NSError *
points to, we also have to pass a pointer to the pointer.
这篇关于什么是双星(例如 NSError **)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!