ios检查空对象

Jac*_*nkr 0 error-handling nserror ios

我通过引用在线找到的一些代码传递了一个错误.该错误作为空对象返回,意味着没有错误.

如果我检查error.code我得到一个糟糕的访问,因为该对象是空的.

如果我检查error == nil我得到一个假,因为error是一个空对象.

如何使用逻辑来查找错误,但是为空?

gra*_*ver 7

错误通常是类型NSError或其子类.它们在以这种方式声明的方法中作为引用传递:

-(void)DoSomeStuff:(NSError **)error;
Run Code Online (Sandbox Code Playgroud)

因此,当您调用一个方法,要求您将引用传递给NSError您时,请按以下方式调用它:

NSError *error = nil;
[self DoSomeStuff:&error];
Run Code Online (Sandbox Code Playgroud)

当此方法完成其工作时,您检查错误对象是否实际上填充了某些内容:

if(error)
{
   //Do some stuff if there is an error.
   //To see the human readable description you can:
   NSLog(@"The error was: %@", [error localizedDescription]);
   //To see the error code you do:
   NSLog(@"The error code: %d", error.code);
}
else //There is no error you proceed as normal
{
  //Do some other stuff - no error
}
Run Code Online (Sandbox Code Playgroud)

PS如果没有出现错误且方法没有按预期运行,则使用此方法实现时出现问题.特别是如果它是一个开源的东西,编码错误很容易出现,所以你可以看一下这个方法的作用,调试甚至修复一些问题......