NSError:使用nil来检测错误是否真的关闭了错误报告? [英] NSError: Does using nil to detect Error actually turn off error reporting?

查看:181
本文介绍了NSError:使用nil来检测错误是否真的关闭了错误报告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我养成了这样编码错误处理的习惯:

I got into the habit of coding my error handling this way:

 NSError* error = nil;
 NSDictionary *attribs = [[NSFileManager defaultManager] removeItemAtPath:fullPath error:&error];
 if (error != nil) {
  DLogErr(@"Unable to remove file: error %@, %@", error, [error userInfo]);
  return; 
 }  

但是查看文档似乎是我弄错了.:

But looking at the documentation It seems like I got this wrong.:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

如果发生错误,返回时将包含一个描述问题的NSError对象.如果您不想获取错误信息,请传递NULL.

If an error occurs, upon return contains an NSError object that describes the problem. Pass NULL if you do not want error information.

从技术上讲,nil和NULL之间没有区别,所以这是否意味着我实际上将其关闭并且永远不会收到错误消息(即使上述示例中的删除操作失败)? 有没有更好的方法对此进行编码?

Technically there is no difference between nil and NULL so does this mean I'm actually turning this off and will never get a error message (even if the delete in the above example did fail) ? Is there a better way to code this ?

谢谢.

推荐答案

首先,以下几行没有任何意义:

First off, the following line doesn't really make sense:

NSDictionary *attribs = [[NSFileManager defaultManager]
 removeItemAtPath:fullPath error:&error];

-removeItemAtPath:error:返回BOOL值,而不是字典.

-removeItemAtPath:error: returns a BOOL value, not a dictionary.

我想我会明白您对NULL值的疑问.但是请仔细注意,方法签名中的error参数如何有2 *:

I think I see what you’re wondering about with the NULL value. Notice carefully though, how there are 2 *'s in the error parameter in the method signature:

- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error

这意味着指向一个指针的指针.传入&error时,就是传入指向NSError的指针的地址. (U,其他人可能可以在这里帮助我,因为当处理指向指针的指针时,我的头仍然开始游动).换句话说,即使将error设置为nil,也没有将error传递给方法,而是将&error传递给了.

That means a pointer to a pointer. When you pass in &error, you are passing in the address of the pointer to the NSError. (Ugh, someone else can probably help me out here, as my head still starts to swim when dealing with pointers to pointers). In other words, even though you have set error to nil, you aren't passing in error to the method, you're passing in &error.

因此,改写后的方法应如下所示:

So, here’s what the re-written method should look like:

// If you want error detection:
NSError *error = nil;
if (![[NSFileManager defaultManager] removeItemAtPath:fullPath
            error:&error]) {
    NSLog(@"failed to remove item at path; error == %@", error);
    // no need to log userInfo separately
    return;
}

// If you don't:
if (![[NSFileManager defaultManager] removeItemAtPath:fullPath
            error:NULL]) {
    NSLog(@"failed to remove item at path");
    return;
}

这篇关于NSError:使用nil来检测错误是否真的关闭了错误报告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆