如何在我的iPhone应用程序中使用NSError? [英] How can I use NSError in my iPhone App?

查看:107
本文介绍了如何在我的iPhone应用程序中使用NSError?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力捕获应用中的错误,我正在研究使用 NSError 。我对如何使用它以及如何填充它感到有些困惑。

I am working on catching errors in my app, and I am looking into using NSError. I am slightly confused about how to use it, and how to populate it.

有人可以举例说明我如何填充然后使用 NSError

Could someone provide an example on how I populate then use NSError?

推荐答案

嗯,我通常做的是我的方法可能在运行时错误输出引用 NSError 指针。如果该方法确实出错了,我可以使用错误数据填充 NSError 引用,并从方法返回nil。

Well, what I usually do is have my methods that could error-out at runtime take a reference to a NSError pointer. If something does indeed go wrong in that method, I can populate the NSError reference with error data and return nil from the method.

示例:

- (id) endWorldHunger:(id)largeAmountsOfMonies error:(NSError**)error {
    // begin feeding the world's children...
    // it's all going well until....
    if (ohNoImOutOfMonies) {
        // sad, we can't solve world hunger, but we can let people know what went wrong!
        // init dictionary to be used to populate error object
        NSMutableDictionary* details = [NSMutableDictionary dictionary];
        [details setValue:@"ran out of money" forKey:NSLocalizedDescriptionKey];
        // populate the error object with the details
        *error = [NSError errorWithDomain:@"world" code:200 userInfo:details];
        // we couldn't feed the world's children...return nil..sniffle...sniffle
        return nil;
    }
    // wohoo! We fed the world's children. The world is now in lots of debt. But who cares? 
    return YES;
}

然后我们可以使用这样的方法。除非方法返回nil,否则甚至懒得检查错误对象:

We can then use the method like this. Don't even bother to inspect the error object unless the method returns nil:

// initialize NSError object
NSError* error = nil;
// try to feed the world
id yayOrNay = [self endWorldHunger:smallAmountsOfMonies error:&error];
if (!yayOrNay) {
   // inspect error
   NSLog(@"%@", [error localizedDescription]);
}
// otherwise the world has been fed. Wow, your code must rock.

我们能够访问错误的 localizedDescription 因为我们为 NSLocalizedDescriptionKey 设置了一个值。

We were able to access the error's localizedDescription because we set a value for NSLocalizedDescriptionKey.

获取更多信息的最佳位置是 Apple的文档。这真的很好。

The best place for more information is Apple's documentation. It really is good.

还有一个很好的,简单的教程 Cocoa是我的女朋友

There is also a nice, simple tutorial on Cocoa Is My Girlfriend.

这篇关于如何在我的iPhone应用程序中使用NSError?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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