如何将NSTextView的格式化内容转换为string

我需要将Mac应用程序中的NSTextView内容传输到iOS应用程序。 我使用XML作为传输的文件格式。

所以我需要将NSTextView(文本,字体,颜色atd)的内容保存为一个string。 有没有办法如何做到这一点?

一种方法是将NSAttributedString值存档。 大纲示例代码直接input答案:

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

读回来:

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

这就是创build和读回文件所需的全部内容。 有创build一个NSData而不是一个文件的匹配方法,你可以将一个NSData转换成一个NSString,或者只是插入一个NSDictionary,并作为一个plist(XML)等序列化。

最好的办法是将文本保存为RFTD,并通过NSAttributedString将其加载到其他文本视图中。

 // Load NSFileWrapper* filewrapper = [[NSFileWrapper alloc] initWithPath: path]; NSTextAttachment *attachment = [[NSTextAttachment alloc] initWithFileWrapper: filewrapper]; NSAttributedString* origFile = [NSAttributedString attributedStringWithAttachment: attachment]; // Save NSData *data = [origFile RTFDFromRange: NSMakeRange(0, [origFile length]) documentAttributes: nil]; [[NSFileManager defaultManager] createFileAtPath: path contents: data attributes:nil];