How to convert formatted content of NSTextView to string

久未见 提交于 2019-12-06 10:11:34

问题


I need transfer content of NSTextView from Mac app to iOS app. I'm using XML as transfered file format.

So I need to save content of NSTextView (text, fonts, colors atd.) as a string. Is there any way how to do that?


回答1:


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];

To read it back:

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

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.




回答2:


Your best bet is probably to store the text as RFTD and load it as such in the other text view via an 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];


来源:https://stackoverflow.com/questions/16237376/how-to-convert-formatted-content-of-nstextview-to-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!