objective-c – 使用NSError检查错误的正确结构

objective-c – 使用NSError检查错误的正确结构,第1张

概述我正在编写各种例程,我正在尽力保持整洁和重构. 我正在创建的方法开始看起来与此代码类似: -(IBAction)buttonPress:(id)sender { // Create Document Shopping List with this document [self doSomething:&error]; if(error) { [NSApp 我正在编写各种例程,我正在尽力保持整洁和重构.

我正在创建的方法开始看起来与此代码类似:

-(IBAction)buttonPress:(ID)sender {    // Create document ShopPing List with this document    [self doSomething:&error];    if(error) {        [NSApp presentError:&error];        return nil;    }    [self doSomethingElse:&error];    if(error) {        [NSApp presentError:&error];        return nil;    }    [self doYetSomethingElse:&error];    if(error) {        [NSApp presentError:&error];        return nil;    }}

我喜欢NSError,但这似乎是处理我所有错误的非常笨拙的方式.

我对替代方法的一些想法:

a)错误检查可以内置到doSomething,doSomethingElse等方法中,但是如果不对返回值进行某种检查,我将无法退出按钮按下方法,这会导致我回到类似的结构.

b)我可以将NSError设置为观察到的键值,但是这个问题感觉非常错误.我非常清楚KVO滥用的可能性,所以我试图在没有它的情况下做任何事情.

当然,我错过了一些非常基本的东西吗?有没有可以帮助我的模式?或者这个结构好吗?

解决方法 我认为这里提出的答案都没有考虑到Apple推荐的做法.

基本上你不应该检查NSError对象来确定是否有问题.通过检查从指向NSError指针的指针返回的值来检查是否存在问题.

从the Apple documentation开始:

important Success or failure is indicated by the return value of the
method. Although Cocoa methods that indirectly return error objects in
the Cocoa error domain are guaranteed to return such objects if the
method indicates failure by directly returning nil or NO,you should
always check that the return value is nil or NO before attempting to
do anything with the NSError object.

总结

以上是内存溢出为你收集整理的objective-c – 使用NSError检查错误的正确结构全部内容,希望文章能够帮你解决objective-c – 使用NSError检查错误的正确结构所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1025345.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-23
下一篇 2022-05-23

发表评论

登录后才能评论

评论列表(0条)

保存