Copying to a Pasteboard

You perform a copy operation by first clearing the existing contents of, then writing the copied objects to, a pasteboard.

There are three steps to performing a copy operation:

  1. Get a pasteboard.

    Typically, you just use the general pasteboard:

    NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
  2. Clear the contents of the pasteboard.

    Typically, you just use the general pasteboard:

    NSInteger changeCount = [pasteboard clearContents];

    The method returns the change count of the pasteboard; you usually don’t need this value.

  3. Write the objects being copied to the pasteboard.

    You pass the objects to write in an array—objects in the array must adopt the NSPasteboardWriting Protocol Reference protocol:

    NSArray *objectsToCopy = <#An array of objects#>;
    BOOL OK = [pasteboard writeObjects:objectsToCopy];

    The method returns NO if the items were not successfully added to the pasteboard.

In many cases, this is as much as you need to do. Note, though, the important prerequisite that objects you write to the pasteboard must adopt the NSPasteboardWriting protocol. Classes that implement the protocol include NSString, NSImage, NSURL, NSColor, NSAttributedString, and NSPasteboardItem. If you want to write an instance of a custom class, either it must adopt the NSPasteboardWriting protocol or you can wrap it in an instance of an NSPasteboardItem—see Custom Data.