Copy NSAttributedString to pasteboard

3.7k Views Asked by At

Brand new to Cocoa and I'm trying to figure out how to copy an NSAttributedString to the pasteboard. I've looked in the docs and not sure if I'm supposed to use a NSPasteboardItem or not.

Here's what I have to copy a regular NSString:

NSPasteboard *pb = [NSPasteboard generalPasteboard];
NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
[pb declareTypes:types owner:self];

[pb setString:@"asdfasdf" forType:NSStringPboardType];

How do I set a NSAttributedString?

Thanks

3

There are 3 best solutions below

0
On BEST ANSWER

You want either NSRTFPboardType or NSRTFDPboardType along with the NSAttributedString's RTFFromRange:documentAttributes:/RTFDFromRange:documentAttributes: and setData on the pasteboard.

0
On
NSPasteboard *paste = [NSPasteboard generalPasteboard];  
[paste clearContents];      
[paste declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
NSMutableAttributedString *aString;// init some string
BOOL success =  [paste writeObjects:[NSArray arrayWithObject:aString]];
0
On

As of Snow Leopard, NSAttributedString (when powered up by AppKit) conforms to NSPasteboardWriting, so you can simply do this:

[pb clearContents];
[pb writeObjects:arrayOfAttributedStrings];

You can send NSArray an arrayWithObject: message if you have only one attributed string you want to put on the pasteboard.

[Edit from the year 2013: Or use the shiny new @[ myAttributedString ] syntax. Works for any number of objects, although they still need to all conform to NSPasteboardWriting in this context.]

This goes for NSString as well. Search the AppKit headers for “NSPasteboardWriting” to find all of the standard Cocoa classes that support it.