swift - 打开和保存在非常简单的基于文档的 Swift 4 应用程序中不起作用

标签 swift xcode macos cocoa swift4

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

@IBOutlet var theTextView: NSTextView!

然后我转到 Storyboard,向其中添加一个 TextView ,并将该 TextView 作为导出连接到 theTextView。我向文档添加数据和读取函数如下:

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 添加到 View Controller ,而不添加任何 socket 或代码,我也会得到完全相同的行为。很明显,Cocoa 不认为我的代码和/或 channel 相关,但我一生都无法弄清楚为什么。我错过了什么?

最佳答案

按照 vadian 的建议,摆脱上面的“抛出”修复了读取方法。

数据方法需要两个修复。首先,显然没有人告诉你 you now need to set permissions能够写入文件。我必须按照链接中的说明执行此操作。

其次,我认为在获取 View Controller 时我需要删除“self”?我不完全确定为什么这有效,但我更多地研究了代码并将其更改为

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)
}

并且成功保存。

关于swift - 打开和保存在非常简单的基于文档的 Swift 4 应用程序中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257155/

相关文章:

swift - 了解 AppDelegate 中的保留计数

ios - 在Swift 3中获取GCD标签

objective-c - IOS:使用 UIAlert 的 cancelButtonTitel 删除 subview

ios - swift 中另一个日期的同一周、月、年中的日期

ios - Swift - 使用协议(protocol)和委托(delegate)将值传递回 ViewController

ios - Cordova 不适用于 iOS 多目标

ruby - Ruby Gem安装Json在Mavericks和Xcode 5.1上失败-未知参数:'-multiply_definedsuppress'

python - 带有 Eclipse 的 TensorFlow

ios - 使用 Swift 以编程方式更改 View - 不起作用

ios - 通过深层链接打开 View Controller 时导航栏消失