Copy NSString to Clipboard

Coming back to the ultimate purpose of this blog… helping my memory! Here is a code snippet to copy an NSString to the macOS clipboard. The snippet below still compiles, but it is written in the pre-ARC style and uses APIs that Apple has since deprecated — a modern version follows.

The original 2010 snippet

-(void)copyToClipboard:(NSString*)str {
  NSPasteboard *pb = [NSPasteboard generalPasteboard];
  NSArray *types = [NSArray arrayWithObjects:NSStringPboardType, nil];
  [pb declareTypes:types owner:self];
  [pb setString: str forType:NSStringPboardType];
}

What’s dated here: NSStringPboardType was replaced by the NSPasteboardTypeString constant, and declareTypes:owner: is the legacy “declare first, write after” pattern that Apple’s NSPasteboard documentation now reserves for macOS 10.5-and-earlier compatibility. On today’s macOS you clear the pasteboard first, then write.

The modern Objective-C version

- (void)copyToClipboard:(NSString *)str {
  NSPasteboard *pb = [NSPasteboard generalPasteboard];
  [pb clearContents];
  [pb setString:str forType:NSPasteboardTypeString];
}

Reading this in Swift

func copyToClipboard(_ string: String) {
    let pasteboard = NSPasteboard.general
    pasteboard.clearContents()
    pasteboard.setString(string, forType: .string)
}

One gotcha that bites everyone coming from iOS: unlike UIPasteboard, where assigning a string replaces the clipboard contents directly, on macOS you must call clearContents() first — otherwise the write doesn’t take effect. For multiple items or non-string types, the modern batch API writeObjects: is the cleaner choice.

Leave a Reply

Your email address will not be published. Required fields are marked *