且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将NSTextView的格式化内容转换为字符串

更新时间:2023-10-06 17:45:22

一种方法是归档NSAttributedString值。大纲示例代码直接键入回答:

One way to do this is to archive the NSAttributedString value. Outline sample code typed directly into answer:

NSTextView *myTextView;
NSString *myFilename;
...
[NSKeyedarchiver archiveRootObject:myTextStorage.textStorage
                            toFile:myFilename];

回读:

myTextView.textStorage.attributedString = [NSKeyedUnarchiver unarchiveObjectWithFile:myFilename];

这就是创建和读回文件所需要的。有匹配的方法创建一个NSData而不是一个文件,你可以将NSData转换为NSString或只是插入一个NSDictionary和serialise作为plist(XML)等。

That's all that is needed to create and read back a file. There are matching methods which create an NSData rather than a file, and you can convert an NSData into an NSString or just insert one into an NSDictionary and serialise that as a plist (XML), etc.