Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy NSAttributedString to pasteboard

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

like image 962
Chris Avatar asked Apr 05 '10 21:04

Chris


3 Answers

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.

like image 59
Peter Hosey Avatar answered Oct 22 '22 23:10

Peter Hosey


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

like image 43
Chuck Avatar answered Oct 22 '22 21:10

Chuck


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]];
like image 1
ERbittuu Avatar answered Oct 22 '22 23:10

ERbittuu