swift - 如何从 NSDictionary writeToURL 获取详细的错误消息?

标签 swift cocoa error-handling nsdictionary

我扩展了一个具有简单导入/导出功能的应用程序,该功能使用 plist 文件来存储导出的对象。为了保存对象,我使用 NSDictionarywriteToURL 方法(沙盒应用程序)。

代码的相关部分如下所示:

savePanel.beginSheetModalForWindow(self.view.window!) { (result) in
    savePanel.orderOut(nil)
    if result == NSFileHandlingPanelOKButton {
        let saveURL = savePanel.URL!
        let values = NSMutableDictionary()
        for propertyDescription in selectedEvent.entity.properties {
            let propertyName = propertyDescription.name
            values[propertyName] = selectedEvent.valueForKey(propertyName)
        }
        if !values.writeToURL(saveURL, atomically: true) {
            // error handling?
        }
    }
}

现在我想知道如果保存文件失败,是否有办法获取详细的错误消息

最佳答案

我没有意识到答案很简单。 NSPropertyListSerialization 不是使用 NSDictionary 上的辅助方法,而是使用 NSPropertyListSerialization,它提供了序列化反序列化 plist 的全套方法。

使用此类,创建一个 NSData 对象,并将该对象写入磁盘。编写 NSData 对象提供所有必需的错误处理。

这里是上面新实现的代码示例:

savePanel.beginSheetModalForWindow(self.view.window!) { (result) in
    savePanel.orderOut(nil)
    if result == NSFileHandlingPanelOKButton {
        let saveURL = savePanel.URL!
        let values = NSMutableDictionary()
        for propertyDescription in selectedEvent.entity.properties {
            let propertyName = propertyDescription.name
            values[propertyName] = selectedEvent.valueForKey(propertyName)
        }
        do {
            let data = try NSPropertyListSerialization.dataWithPropertyList(values, format: .XMLFormat_v1_0, options: NSPropertyListWriteOptions())
            try data.writeToURL(saveURL, options: [.DataWritingAtomic])
        } catch let error as NSError {
            dispatch_async(dispatch_get_main_queue()) {
                self.view.window!.presentError(error)
            }
        } catch {
            let unknownError = NSError(domain: kAppErrorDomain, code: 201, userInfo: [
                NSLocalizedDescriptionKey: "Unknown error while writing the export file."
            ])
            dispatch_async(dispatch_get_main_queue()) {
                self.view.window!.presentError(unknownError)
            }
        }
    }
}

关于swift - 如何从 NSDictionary writeToURL 获取详细的错误消息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36790371/

相关文章:

excel - Excel 通过 Outlook 发送电子邮件时如何处理错误?

ios - 核心数据最佳实践——我在利用 C.D.正确有效? - iOS swift

ios - 现有的 Xcode/Swift3 应用程序突然无法识别 Parse 框架

swift - 禁用/启用 NSMenu 项

cocoa - 在 MAC OSx 上将 FLV 转换为 MP4 视频文件

objective-c - 查找哪个类响应特定消息

asp.net-mvc - 如何将服务器错误的 http 状态代码捕获到 ASP.NET MVC 中的通用自定义错误 View 中

Swift 3 - 在 map 上显示坐标

cocoa - 在 Cocoa 中设置权限

r - R保存来自嵌套的for循环的结果