views:

137

answers:

2

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

+2  A: 

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

Chuck
+2  A: 

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.

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

Peter Hosey