iphone - 如何在我的 iPhone 应用程序中使用 NSError?

我正在处理我的应用程序中的错误,我正在研究使用 NSError。我对如何使用它以及如何填充它感到有些困惑。

有人可以提供一个关于我如何填充然后使用 NSError 的示例吗?

最佳答案

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

例子:

- (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,否则不要费心检查错误对象:

// 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 设置了一个值。

了解更多信息的最佳位置是Apple's documentation .确实不错。

Cocoa Is My Girlfriend 上还有一个不错的简单教程.

https://stackoverflow.com/questions/4654653/

相关文章:

ios - 卸载应用程序时删除钥匙串(keychain)项目

ios - 在 Swift 中使用 UI_USER_INTERFACE_IDIOM() 检测当前设备

objective-c - 开始使用 instancetype 而不是 id 会有好处吗?

ios - 突出显示时如何更改 UIButton 的背景颜色?

ios - 如何更改导航栏上 "back"按钮的标题

objective-c - 实现 API 时如何避免在 block 中捕获 self ?

ios - 您可以将 UIGestureRecognizer 附加到多个 View 吗?

ios - 从 "bouncing"垂直停止 UIWebView?

ios - 设置自定义 UITableViewCells 高度

ios - setNeedsLayout 与 setNeedsUpdateConstraints 和