【问题标题】:Saving a file when using NSDocument使用 NSDocument 时保存文件
【发布时间】:2009-12-31 17:51:14
【问题描述】:

我正在使用 NSDocument 创建一个应用程序。 MyDocument.xib 在 NSScrollView 中只有一个 NSTextView。当我执行 ⌘S 保存它时,我收到一条错误消息('无法将文档“Untitled”保存为“Untitled.rubytext”。')。如何让我的应用程序将其保存为 RTF 文件?我的意思是使用 NSDocument(我猜是 dataRepresentationOfType 但我不确定?)

提前致谢。

【问题讨论】:

    标签: cocoa nsdocument


    【解决方案1】:

    我想补充一点,链接页面中dataForType:error: 的示例实现包含一些过时或完全不准确的信息。这是我发送给 Apple 的报告:

    dataOfType:error: 的示例实现如下:

    - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
        [textView breakUndoCoalescing];
        NSData *data = [textView dataFromRange:NSMakeRange(0, [[textView textStorage] length])
                                 documentAttributes:nil
                                 error:outError];
        if (!data && outError) {
            *outError = [NSError errorWithDomain:NSCocoaErrorDomain
                                    code:NSFileWriteUnknownError userInfo:nil];
        }
        return data;
    }
    

    这有一些问题。首先,NSTextView 没有 dataFromRange:documentAttributes:error: 方法。这应该是[text dataFromRange…],假定文档中指定的数据结构。

    其次,根据NSAttributedString的文档,dataFromRange:documentAttributes:error:“需要一个文档属性字典字典,至少指定 NSDocumentTypeDocumentAttribute 来确定要写入的格式。”

    所以,示例实现至少应该是这样的

    - (NSData *)dataOfType:(NSString *)typeName error:(NSError **)outError {
        [textView breakUndoCoalescing];
        NSData *data = [text dataFromRange:NSMakeRange(0, [[textView textStorage] length])
                                 documentAttributes:[NSDictionary dictionaryWithObjectsAndKeys:NSPlainTextDocumentType, NSDocumentTypeDocumentAttribute, nil]
                                 error:outError];
        if (!data && outError) {
            *outError = [NSError errorWithDomain:NSCocoaErrorDomain
                                    code:NSFileWriteUnknownError userInfo:nil];
        }
        return data;
    }
    

    或其他一些适用于 RTF 或其他文本值类型的字典值。

    虽然看起来 OP 在发布时可能没有看到该文档,但由于文档已损坏,因此简单地链接到该文档并没有人们想象的那么大的帮助。尽管我已经逐字复制了 Apple 的实现,但我在相当长的一段时间后发现了这一点。

    希望这对其他人有所帮助。

    【讨论】:

      【解决方案2】:

      Apple answered this for you 很久以前。

      【讨论】:

      • 此链接不存在。这就是为什么您应该在评论中包含解决方案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-18
      • 1970-01-01
      相关资源
      最近更新 更多