Tru*_*an1 7 error-handling nserror swift3
在Swift 3中,引入了RecoverableError协议,但是关于如何使用它的文档很少.
这听起来像是为失败的进程提供重试功能的本机方式,这可能非常有用.这是如何使用的一个例子?
您可以利用的一件事RecoverableError是适用于 macOS 的基于文档的应用程序。
创建一个新项目,macOS > Cocoa,选中“创建基于文档的应用程序”。
定义您自己的错误类型,符合RecoverableError.
enum MyError {
case documentSavingError
//...
}
extension MyError: RecoverableError {
var recoveryOptions: [String] {
return [
"Retry", "Ignore"
]
}
func attemptRecovery(optionIndex recoveryOptionIndex: Int) -> Bool {
if recoveryOptionIndex == 0 {//for "Retry"
var result = false
switch self {
case .documentSavingError:
//Attempt "Retry" recovery for the failed operation, and return the result
//...
print("assume recovery attempt successfully finished...")
result = true
//...
}
return result
} else if recoveryOptionIndex == 1 {//for "Ignore"
return true
}
fatalError("something wrong...")
}
}
Run Code Online (Sandbox Code Playgroud)修改data(ofType:)Document.swift 中的方法以引发错误。
override func data(ofType typeName: String) throws -> Data {
//throw RecoverableError
throw MyError.documentSavingError
}
Run Code Online (Sandbox Code Playgroud)在当前基于文档的应用程序中,您还需要一个技巧......
创建一个新的 swift 代码来子类化NSApplication。
import AppKit
@objc(Application)
class Application: NSApplication {
override func presentError(_ error: Error, modalFor window: NSWindow, delegate: Any?, didPresent didPresentSelector: Selector?, contextInfo: UnsafeMutableRawPointer?) {
//print(error)
let underlyingError = (error as NSError).userInfo[NSUnderlyingErrorKey] as? Error ?? error
//print(underlyingError)
super.presentError(underlyingError, modalFor: window, delegate: delegate, didPresent: didPresentSelector, contextInfo: contextInfo)
}
}
Run Code Online (Sandbox Code Playgroud)
RecoverableError当前基于文档的应用程序会在通常的 中进行包装NSError,因此,如果没有它,自动生成的功能NSDocumentErrorRecoveryAttempter将无法正常工作。
不要忘记修改 Info.plist 以指定此类作为其主体类。
构建并运行应用程序,然后在出现文档窗口时,选择“文件”>“保存...”,然后单击保存表中的“保存”。
您可能会发现您的RecoverableError工作方式...
因此,当您的应用程序已经实现了错误处理编程指南RecoverableError中描述的标准恢复功能时,它非常有用。它的简介说得很清楚:
重要提示:该类
NSError在 OS X 和 iOS 上都可用。但是,错误响应程序和错误恢复 API 和机制仅在应用程序工具包 (OS X) 中可用。
| 归档时间: |
|
| 查看次数: |
427 次 |
| 最近记录: |