首页 > 解决方案 > 打开和保存在非常简单的 Swift 4 基于文档的应用程序中不起作用

问题描述

不久前我在 Swift 2 中进行了一些 Swift 编程,现在正在尝试使用 Swift 4。也许我遗漏了一些非常明显的东西,但我一辈子都无法打开一个极其简单的基于文档的文本编辑器应用程序或正确保存文件。我制作了基于文档的应用程序并将此代码添加到 ViewController 类中:

@IBOutlet var theTextView: NSTextView!

然后我转到情节提要,向其中添加一个文本视图,并将该文本视图连接到 theTextView 作为插座。我向 Document 添加了数据和读取功能,如下所示:

override func data(ofType typeName: String) throws -> Data {

    if let vc = self.windowControllers[0].contentViewController as? ViewController {
        return vc.theTextView.string.data(using: String.Encoding.utf8) ?? Data()
    }
    else {
        return Data()
    }

}

override func read(from data: Data, ofType typeName: String) throws {

    if let s = String(data: data, encoding: String.Encoding.utf8) {
        string = s
    }

    throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}

程序编译并运行。但是每当我尝试保存时,没有保存对话框出现并且应用程序无法退出(我必须从 Xcode 中停止它)。每当我尝试以我为应用程序设置的格式打开文件时(即使它只是 .txt),我都会收到错误消息“无法打开文档 [文件名]。” 即使我所做的只是将 TextView 添加到视图控制器,而没有添加任何插座或代码,我也会得到完全相同的行为。很明显 Cocoa 没有认识到我的代码和/或网点是相关的,但我终其一生都无法弄清楚原因。我错过了什么?

标签: swiftxcodemacoscocoaswift4

解决方案


正如 vadian 建议的那样,摆脱上面的“抛出”固定了 read 方法。

数据方法需要两个修复。首先,显然没有人告诉您现在需要设置权限才能写入文件。我必须按照链接上的说明进行操作。

其次,我认为在获取视图控制器时我需要放弃“自我”?我不完全确定为什么会这样,但我更多地使用代码并将其更改为

var viewController: ViewController? {
    return windowControllers[0].contentViewController as? ViewController
}

override func data(ofType typeName: String) throws -> Data {
    let textView = viewController?.theTextView
    if let contents = textView?.string.data(using: String.Encoding.utf8)
    {
        return contents
    }
    throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}

这成功地保存了


推荐阅读