Buy*_*ian 0 cocoa-touch objective-c
可能重复:
为什么在Cocoa编程中传递错误而不是错误?
我有一个问题,我似乎无法找到答案......
我正在使用SBJsonParser,我发现有一行代码令人费解:
NSError *error;
self.jsonData = [jsonParser objectWithString:responseString error:&error];
Run Code Online (Sandbox Code Playgroud)
错误参数前面的&是什么?(&错误)?
在Objective-C中,就像在C中一样,&是"address-of operator",它返回其参数的地址.要了解更多相关信息,我建议您阅读The C Book中的这一简短章节.
这是一个如何使用运算符的示例,以获得更好的想法:
#include <stdio.h>
// define a function that takes a pointer to an integer as argument
void change_value_of_int(int* int_to_change) {
// change the value to which the argument points
*int_to_change = 5;
}
int main() {
// create a stack variable
int test_int = 10;
// pass the address of test_int to the function defined earlier
change_value_of_int(&test_int);
// now the value of test_int is 5
printf("%d\n", test_int);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
请注意,该change_value_of_int()函数要求第一个参数是指向 int 的指针,而不是int,因此您无法使用它来调用它change_value_of_int(test_int).你必须向它发送地址的的test_int变量,而不是变量本身(因为如果您发送的变量的副本,它不能改变它).
与NSError*示例相同.jsonParser期望地址的一个NSError*,而不是一个NSError*,因此该方法被定义为:
- (id)objectWithString:(NSString*)jsonrep error:(NSError**)error;
Run Code Online (Sandbox Code Playgroud)
查看头文件和实现,看看它是如何使用的.你的值error(*error= error参数指向的东西的值)成为返回值[errorTrace lastObject].
它是运算符的地址,可以在C,C++和Objective-C中找到.
在您的示例中,&error产生一个NSError **(即指向指针的指针).
这在C中是常见的(并且,通过扩展,Objective-C):使用指针模拟传递引用,这意味着您必须将要修改的对象的地址(在本例中为另一个指针)传递给一个功能.