Objective-C中的& error(NSError)构造的解释(使用未声明的标识符'错误#39;)

时间:2014-09-12 01:58:25

标签: ios objective-c parse-platform nserror

我是iOS开发的新手,我正在开发一个类似于Instagram的应用程序,以便教我基础知识。我正在通过AnyPic Tutorial通过parse.com工作,因为它很有用,但是在AppDelegate.m中,有一个函数,代码发出请求来解析某些facebook数据,并返回一些数据。我的问题是以下几行代码:

PFQuery *facebookFriendsQuery = [PFUser query];
[facebookFriendsQuery whereKey:kPA_UserFacebookIDKey containedIn:facebookIds];

NSArray *facebookFriends = [facebookFriendsQuery findObjects:&error];

// This if statement gives me the following error: 
// "use of undeclared identifier 'error'"       
if (!error){ }

这个结构:

NSArray *facebookFriends = [facebookFriendsQuery findObjects:&error];

if (!error){ }

看起来很简单,但它在我的代码中给出了一个错误(使用未声明的标识符'错误'),但在AnyPic文件中没有出现警告。

那么有人可以解释一下这个构造是什么(& error),也许也就是为什么我可能会得到这个'未声明的标识符'错误?

// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

EDIT(2014年9月14日):因为这篇文章的标题是“在Objective-C中对&错误(NSError)构造的解释”,我想我实际上会解释我学到的东西,以防万一将来可能会对其他人有所帮助。现在对我来说很傻,我失踪的是error变量声明,而if (!error) {}正在评估错误变量是否为零或者非零,但混淆似乎是有道理的,因为在PHP中,我非常熟悉的一种语言,可以在函数调用中分配一个不存在的变量,并将其提升到调用它的函数的范围内。例如:

// In PHP 

preg_match_all("/myregex/", $someString, $matches);
if ($matches) {
    // pregmatch has found some matches, and now there is a variable
    // named $matches available to the same scope where preg_match_all was called
}  

所以当我在Objective-C中看到类似的东西(但语法不完全相同)时:

// In Objective-C

NSArray *myArray = [self getObjects:&error];
if(!error) {
    // This is a compiler error, because the error variable
    // doesn't exist at this point, because Objective-C won't 
    // let you assign variables in this way
}

所以解决方案是要记住,PHP和Objective-C是非常不同的,并且使用&运算符将值(通过引用传递)转换为变量的正确语法就像这样:

// In Objective-C

NSError *error = nil; // <-- THIS IS EXTREMELY IMPORTANT!
NSArray *myArray = [self getObjects:&error];
    if(!error) {
        // Now the compiler won't complain, because the error variable 
        // has been assigned. This block of code will run if the error variable
        // is still equal to nil. Which means the [self getObjects:] ran without error.
    } else {
        // if error == YES, it means that the [self getObjects:] function
        // encountered an error and has assigned the reference to the error into 
        // the error variable you previously assigned to nil, allowing it to 
        // evaluate as non-nil
    }

希望这可能会帮助那些遇到与我同样困惑的人。

1 个答案:

答案 0 :(得分:2)

您收到此错误,因为未定义变量error

AppDelegate.m从第459行开始,你会发现声明的错误变量。然后在第472行发生错误时更改该错误。然后在第474行,条件检查该变量以确定一切是否正常并继续。

NSError *error = nil; //line 459

NSArray *anypicFriends = [query findObjects:&error]; //line 472

if (!error) { }  // line 474