How to convert NSAttributedString to NSData?


I have an NSAttributedString that I want to write back into the pasteboard.

The general NSPasteboard has different types, the NSAttributedString with attachments does fit to NSPasteboardTypeRTFD

I know how to write into the pasteboard:

    NSData * __strong newContent = ... // how?
    NSPasteboard * __strong pboard = [NSPasteboard generalPasteboard];
    NSString * __strong type = NSPasteboardTypeRTFD;
    [pboard setData:newContent forType:type];

But how to convert from a given NSAttributedString two a RTF NSData (which should then fit the type readable by the pasteboard)?

asked Nov 5 ’13 at 21:41
RTFDFromRange:documentAttributes: maybe? –  CRD Nov 5 ’13 at 22:08
Can you give an example code with a range example for a complete NSAttributedString? – Viktor Lexington Nov 5 ’13 at 22:21
see added answer –  CRD Nov 5 ’13 at 22:36

add comment

2 Answers

You can do this with RTFDFromRange:documentAttributes:

NSAttributedString *text;
NSData *rtfd = [text RTFDFromRange:NSMakeRange(0, text.length)
answered Nov 5 ’13 at 22:36

what do you want the data to be, do you just want the text?
Then you can convert to an NSString with -string

Edit: I couldn’t find the methods because they are in a category: NSAttributedString Application Kit Additions

Thank to @CRD for pointing me there.

I think it is interesting that it states for -RTFDFromRange:documentAttributes: it states that the documentAttributes is a required dictionary, then it says:

If there are no document-level attributes, dict can be nil.

The companion guide can be found here

answered Nov 5 ’13 at 21:42
Grady Player
Everything what NSAttributedString could be, a styled text with image attachments for example – Viktor Lexington Nov 5 ’13 at 22:12

add comment


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s