检查 BOOL 状态就足够了吗?还是我们还应该检查错误?

Is it enough to check for BOOL status or should we check for Error as well?

当一个方法 returns 同时出现 BOOL 和 Error 时,检查 BOOL 状态就足够了吗?还是我们应该为 Error 添加附加条件?

例如,以下方法 returns 布尔值和错误(如果有)。

-(BOOL)canEvaluatePolicy:(LAPolicy)policy error:(NSError * __autoreleasing *)error;

现在我应该写

 BOOL biometricsAvailable = [context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error];
    available = (error == nil && biometricsAvailable);

BOOL biometricsAvailable = [context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:&error];

够了吗?

两种情况不同。这取决于你的要求。

如果您只使用 BOOL,那么您只会获得请求的状态。无论是失败还是成功,你都可以根据它执行 task.But 你将无法知道错误是什么。

要知道错误到底是什么,您应该使用第一种方法。如果你想知道。

不,检查 return 值应该就足够了。但是当 NO 被 return 编辑时,您可以查看 error 变量以了解原因。

苹果已经声明你应该检查方法的return值,只有当这是NOnil时你才能检查错误, 因为 SDK 可以在 error 变量中放置一些奇怪的值。

查看文档Programming with Objective-C - Dealing with Errors

定义 "enough"。为了什么?

约定的约定是,如果出现问题,应返回 NO,如果您传入 NSError 指针,它将被填充。如果你想对错误做些什么,你必须检查它,但惯例说永远不会有提供错误但返回 YES 的情况(如果返回 YES甚至不应该触摸指针),或者返回 NO 并且没有错误。这种约定在Cocoa中无处不在,并且已经稳定了几十年,而且由于Swift只是基于他们的错误处理这个模型,我认为这更不可能改变。

这里的文档里描述的很清楚; https://developer.apple.com/library/prerelease/ios/documentation/LocalAuthentication/Reference/LAContext_Class/index.html#//apple_ref/occ/instm/LAContext/canEvaluatePolicy:error:,

Return Value

true if the policy can be evaluated, false otherwise.

Parameters

policy
The policy to evaluate.
error
On input, a pointer to an error object. If an error occurs, this pointer is set to an actual error object containing the error information. You may specify nil for this parameter if you do not want the error information.

因此,这意味着布尔值 return 会告诉您评估是否成功。如果失败,您的错误对象将被设置,其中将有关于失败的描述。