在NSAttributedString保存自定义属性 [英] Saving custom attributes in NSAttributedString

查看:443
本文介绍了在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,并将其写入文件。后来,当我打开该文件,并将其恢复到文本查看我的自定义属性都不见了!制定出整个计划为我的自定义属性后,我发现,自定义属性不会被保存为您服务。看看这里的重要注意事项:<一href=\"http://developer.apple.com/mac/library/DOCUMENTATION/Cocoa/Conceptual/AttributedStrings/Tasks/RTFAndAttrStrings.html\">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:错误:的方法 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 协议存档您的归属字符串,将preserve自定义属性:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆