Writing a string to NSPasteBoard

元气小坏坏 提交于 2019-12-02 19:03:56

Here is the working version of the method:

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    [pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
    return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}

Swift 2:

Copy a string to the general pasteboard with Swift 2:

let pasteboard = NSPasteboard.generalPasteboard()
pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
pasteboard.setString("Hello", forType: NSPasteboardTypeString)

Apple is suggesting people move away from NSStringPboardType and use NSPasteboardTypeString instead.

As of 10.6, the following implementation is also possible:

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    [pasteBoard clearContents];
    return [pasteBoard writeObjects:[NSArray arrayWithObject:stringToWrite]];
}

It's important to notice that #clearContents has to be called before something new can be written to the pasteboard, otherwise #writeObjects: keeps returning NO.

The new #writeObjects: methods is possible for objects that conform to the NSPasteboardWriting protocol. There's also an NSPasteboardReading Protocol, but using it wouldn't make the implementation any simpler.

Before you copy a string on NSPasteboard it's better to clear the contents and then save.

Swift 4

    // Set string
    NSPasteboard.general.clearContents()
    NSPasteboard.general.setString("I copied a string", forType: .string)
    // Read copied string
    NSPasteboard.general.string(forType: .string)

Objective-C

    // Set string
    [[NSPasteboard generalPasteboard] clearContents];
    [[NSPasteboard generalPasteboard] setString:@"I copied a string" forType:NSPasteboardTypeString];
    // Read string
    [[NSPasteboard generalPasteboard] stringForType:NSPasteboardTypeString];

And also there are other available types for copying items on NSPasteboard. Like:

  • NSPasteboardTypeString
  • NSPasteboardTypePDF
  • NSPasteboardTypeTIFF
  • NSPasteboardTypePNG
  • NSPasteboardTypeRTF

You can find more details on https://developer.apple.com/documentation/appkit/nspasteboardtype.

Swift 4 version:

NSPasteboard.general.clearContents()
NSPasteboard.general.setString("Hello World", forType: .string)

For the record, to copy a string to the system clipboard, you can use

NSPasteboard *pasteBoard = [NSPasteboard generalPasteboard];
[pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
[pasteBoard setString:string forType:NSStringPboardType];

This works on Mojave 10.14.5 and does not use any deprecated APIs:

NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard declareTypes:[NSArray arrayWithObjects:NSPasteboardTypeString, nil] owner:nil];
[pasteboard setString:@"Hello clipboard!" forType:NSPasteboardTypeString];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!