我正在努力捕捉我的应用程序中的错误,我正在考虑使用NSError.我对如何使用它以及如何填充它有点困惑.

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

推荐答案

嗯,我通常做的是让我的方法引用一个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的很好的、简单的教程.

Ios相关问答推荐

找不到com.google.vr:sdk-base:1.180.0

Flutter中抛出后期应用错误

构建iOS项目失败.我们运行了";xcodeBuild";命令,但它退出并返回错误代码65-expo reaction ative

如何在iPhone 15上消除.NET Maui中状态栏和页面之间的差距

在许多UIButton中对齐文本,即使SF Symbols(或其他图像)具有不同的宽度?

withTaskGroup不适用于CLGeocoder

如何使用自定义数据源在本地react 本机 ios 应用程序中加载 Tradingview 小部件?

在 Swift 项目中使用情节提要加载 obj-c 文件

Swift:判断 Foundation (NS)Errors 与自定义协议的一致性

如何在 SwiftUI 视图中显示协议视图?

Xcode14 启动时崩溃:dyld:库未加载:/usr/lib/swift/libswiftCoreGraphics.dylib

在标签中显示多个计数器但在同一屏幕(Swift,IOS)

clipShape swift的三元

来自 c++ 的runtime_error未在 iOS 中捕获

UIImageView 使用 CGAffineTransform 错误旋转

UICollectionView - 水平滚动,水平布局?

iOS 中的 Crashlytics 不会继续通过 Fabric 应用程序中的构建您的项目

SRCROOT 和 PROJECT_DIR 有什么区别?

iOS7 UITextView contentsize.height 替代

请在您的 Podfile 中为此目标指定一个平台?