【问题标题】:How to get data from NSDocument's read method如何从 NSDocument 的 read 方法中获取数据
【发布时间】:2019-09-16 11:04:00
【问题描述】:

我在尝试将“数据”放到 NSPasteboard 上时遇到了困难。我所说的“数据”是指特定 PasteboardType 格式以外的类型:文本、HTML、图像等。(实际上是 MIDI 数据。)

override func copy() -> Any {
  let pboard = NSPasteboard.general
    pboard.clearContents()
    pboard.setData(data, forType: .typeMidi)
        return true
    }

当我尝试输入数据时,我得到:

无法将“(String) throws -> Data”类型的值转换为预期的元素类型“NSPasteboardWriting”。

这可能是因为我一直在尝试使用 NSDocument 的数据方法,但事实证明这只是为了写入磁盘。

数据需要来自读取函数:

override func read(from data: Data, ofType typeName: String) throws {
    self.theMIDIPlayer = try AVMIDIPlayer.init(data: data, soundBankURL: nil)
    if self.theMIDIPlayer == nil {
         throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
}

但似乎read 函数的参数不是NSDocument 的data 函数(仅与写作有关)。我不知道这些论点从何而来。

self.myData = data 之类的内容添加到读取函数(试图获取有用属性中的数据)会产生“预期模式”错误。

【问题讨论】:

  • 你的data(ofType typeName: String) 函数没有返回任何东西。
  • @Koen 当我在读取功能中使用它时它可以工作。我将把它添加到问题中。
  • 如果它在其他地方工作并不意味着它一定是正确的。
  • read(from:ofType:NSDocument 相关。 API 与您的 MIDI 数据有什么关系?
  • @vadian Midi 文件是应用程序的文档。这段代码都在 Document.swift 中

标签: swift macos nsdocument


【解决方案1】:

已解决:问题是使用copy() 而不是copy(_:) 的小学生错误。

Vadian 现在删除的答案有助于创建自定义粘贴板类型。

完整(相关)代码如下:

extension NSPasteboard.PasteboardType {
    static let typeMidi = NSPasteboard.PasteboardType(rawValue: "public.midi-audio")
}

class Document: NSDocument {

    var theMIDIPlayer: AVMIDIPlayer?
    var myData: Data?

    @IBAction func copy(_: Any)  {
      let pboard = NSPasteboard.general
        pboard.clearContents()
        pboard.setData(myData, forType: .typeMidi)
    }

    override func read(from data: Data, ofType typeName: String) throws {
        self.theMIDIPlayer = try AVMIDIPlayer.init(data: data, soundBankURL: nil)
        self.myData = data
        if self.theMIDIPlayer == nil {
             throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
    }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多