Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing a string to NSPasteBoard

I cannot get this method to return YES:

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}

I have verified that stringToWrite is coming through properly, the method just always returns NO.

Any ideas?

Here is the rest of the class:

@interface ClipBoard : NSObject {
    NSPasteboard *pasteBoard;
}

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite;
- (NSString *) readFromPasteBoard;
@end

@implementation ClipBoard
- (id) init
{
    [super init];
    pasteBoard = [NSPasteboard generalPasteboard];
    return self;
}

- (BOOL) writeToPasteBoard:(NSString *)stringToWrite
{
    return [pasteBoard setString:stringToWrite forType:NSStringPboardType];
}

- (NSString *) readFromPasteBoard
{
    return [pasteBoard stringForType:NSStringPboardType];
}

@end

like image 545
joshwbrick Avatar asked Feb 28 '09 20:02

joshwbrick


4 Answers

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];
}
like image 163
joshwbrick Avatar answered Nov 02 '22 18:11

joshwbrick


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)
like image 27
Sebastian Avatar answered Nov 02 '22 19:11

Sebastian


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.

like image 17
abdullahselek Avatar answered Nov 02 '22 18:11

abdullahselek


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

like image 15
Jason Fuerstenberg Avatar answered Nov 02 '22 18:11

Jason Fuerstenberg