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
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];
}
Copy a string to the general pasteboard with Swift 2:
let pasteboard = NSPasteboard.generalPasteboard()
pasteboard.declareTypes([NSPasteboardTypeString], owner: nil)
pasteboard.setString("Hello", forType: NSPasteboardTypeString)
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:
You can find more details on https://developer.apple.com/documentation/appkit/nspasteboardtype.
Apple is suggesting people move away from NSStringPboardType and use NSPasteboardTypeString instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With