在NSAttributedString中保存自定义属性 [英] Saving custom attributes in NSAttributedString
问题描述
我需要在NSTextView中为所选文本添加自定义属性。所以我可以通过获取属性字符串的选择,添加一个自定义属性,然后用我新的属性字符串替换选择。
I need to add a custom attribute to the selected text in an NSTextView. So I can do that by getting the attributed string for the selection, adding a custom attribute to it, and then replacing the selection with my new attributed string.
现在我将文本视图的属性字符串作为NSData并将其写入文件。后来当我打开该文件,并将其还原到文本视图我的自定义属性已经走了!完成我的自定义属性的整个方案后,我发现自定义属性不会为您保存。请查看此处的重要注意事项: http:/ /developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/AttributedStrings/Tasks/RTFAndAttrStrings.html
So now I get the text view's attributed string as NSData and write it to a file. Later when I open that file and restore it to the text view my custom attributes are gone! After working out the entire scheme for my custom attribute I find that custom attributes are not saved for you. Look at the IMPORTANT note here: http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/AttributedStrings/Tasks/RTFAndAttrStrings.html
所以我不知道如何使用此自定义属性保存和恢复我的文档。任何帮助?
So I have no idea how to save and restore my documents with this custom attribute. Any help?
推荐答案
保存 NSAttributedString
的正常方法是使用RTF和RTF数据是 -dataFromRange:documentAttributes:error:方法
NSAttributedString
生成
The normal way of saving an NSAttributedString
is to use RTF, and RTF data is what the -dataFromRange:documentAttributes:error:
method of NSAttributedString
generates.
但是,RTF格式不支持自定义属性。相反,您应该使用 NSCoding
协议归档您的属性字符串,这将保留自定义属性:
However, the RTF format has no support for custom attributes. Instead, you should use the NSCoding
protocol to archive your attributed string, which will preserve the custom attributes:
//asssume attributedString is your NSAttributedString
//encode the string as NSData
NSData* stringData = [NSKeyedArchiver archivedDataWithRootObject:attributedString];
[stringData writeToFile:pathToFile atomically:YES];
//read the data back in and decode the string
NSData* newStringData = [NSData dataWithContentsOfFile:pathToFile];
NSAttributedString* newString = [NSKeyedUnarchiver unarchiveObjectWithData:newStringData];
这篇关于在NSAttributedString中保存自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!