像 Swift 一样使用 Enum 进行 Objective-C 错误处理

标签 objective-c swift error-handling enums

我刚刚熟悉 Objective-C,因为我的主要语言是 Swift。我找不到使用 Objective-c 枚举处理错误情况的最佳方法,因为我可以使用 Swift 做同样的事情。

例如,在 Swift 中,我可以使用方便的枚举来处理错误,如下所示:

import Foundation

public enum ErrorCases: Error, LocalizedError {
    case invalidURL(String)
    case JSONStringConversionError(String)
    case JSONStringifyError(Any?)
    case hashArrayCastError(Any)

    public var localizedDescription: String {
        switch self {
        case .invalidURL(let url): return "Invalid URL: \(url)."
        case .JSONStringConversionError(let jsonString): return "Cannot convert string to JSON, string: \(jsonString)."
        case .JSONStringifyError(let data): return "Cannot stringify JSON dictionary with 'Any' data to a string, data: \(String(describing: data))."
        case .hashArrayCastError(let hashArray): return "Cannot cast JSON with '#' key to an arrray of 'Any' objects from massage, JSON: \(hashArray)."
        }
    }
}

现在我可以像这样使用该枚举:

if error != nil {
    self.onError(error: ErrorCases.invalidURL(self.mUrl))
}

您能否推荐更好的方法来实现相同的错误处理,但使用 Objective-C! 感谢您的帮助。

最佳答案

在 objC 中,你不能真正做同样的事情,因为枚举不能有关联的值。 objC 中的错误处理主要是通过 NSError 对象来完成的。 对于您的情况,我建议创建一个枚举:

typedef NS_ENUM(NSInteger, ErrorCaseType) {
    ErrorCaseTypeInvalidURL,
    ErrorCaseTypeJSONStringConversionError,
    ErrorCaseTypeJSONStringifyError,
    ErrorCaseTypeHashArrayCastError
};

然后出现错误时,创建一个错误对象:

error = [NSError errorWithDomain:@"com.myapp.mydomain" 
                                code: ErrorCaseTypeInvalidURL
                            userInfo:@{NSLocalizedDescriptionKey : NSLocalizedString(@"Oops...", nil)}];

收到错误时,您可以访问[错误代码]值并根据您的枚举进行检查或/并显示[error localizedDescription]文本。

您可以在此处找到有关错误对象的更多信息: https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ErrorHandlingCocoa/CreateCustomizeNSError/CreateCustomizeNSError.html#//apple_ref/doc/uid/TP40001806-CH204-BAJIIGCC

关于像 Swift 一样使用 Enum 进行 Objective-C 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49502659/

相关文章:

ios - 如何在代码中关闭或打开自动布局

ios - 如何显示AVPlayer播放音频的进度

ios - CLLocationManager startMonitoringForRegion 在 ios 8.4 上崩溃

typescript - 在文件树中突出显示 Vim 中 TypeScript 错误文件的解决方案

r - match.names(clabs, nmi) 中的错误 - 线性规划模型 - R

iphone - 在给定 cell.imageView 的情况下发现 UITableViewCell

Iphone 遮蔽颜色 : Remove background color

ios - SwiftUI-从JSON文件显示数组

swift - Ubuntu 14.04 (Windows) 上的 Vapor 设置错误

c - 如何像 gets_s() 一样调用无效的处理函数?