Question

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

Was it helpful?

Solution

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

OTHER TIPS

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.

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]];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top