我想补充一点,链接页面中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 的实现,但我在相当长的一段时间后发现了这一点。
希望这对其他人有所帮助。