How to convert formatted content of NSTextView to

2020-07-24 03:43发布

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?

2条回答
Deceive 欺骗
2楼-- · 2020-07-24 04:16

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.

查看更多
手持菜刀,她持情操
3楼-- · 2020-07-24 04:40

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];
查看更多
登录 后发表回答