我无法让这个方法返回YES:
- (BOOL) writeToPasteBoard:(NSString *)stringToWrite { return [pasteBoard setString:stringToWrite forType:NSStringPboardType]; }
我已经验证stringToWrite正确通过,该方法总是返回NO.
有任何想法吗?
这是课程的其余部分:
@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]; }
@结束
以下是该方法的工作版本:
- (BOOL) writeToPasteBoard:(NSString *)stringToWrite { [pasteBoard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil]; return [pasteBoard setString:stringToWrite forType:NSStringPboardType]; }
使用Swift 2将字符串复制到常规粘贴板:
let pasteboard = NSPasteboard.generalPasteboard() pasteboard.declareTypes([NSPasteboardTypeString], owner: nil) pasteboard.setString("Hello", forType: NSPasteboardTypeString)
Apple建议人们远离NSStringPboardType并使用NSPasteboardTypeString.
从10.6开始,以下实现也是可能的:
- (BOOL) writeToPasteBoard:(NSString *)stringToWrite { [pasteBoard clearContents]; return [pasteBoard writeObjects:[NSArray arrayWithObject:stringToWrite]]; }
重要的是要注意,在将新内容写入粘贴板之前必须调用#clearContents,否则#writeObjects:保持返回NO.
对于符合NSPasteboardWriting协议的对象,可以使用新的#writeObjects:方法.还有一个NSPasteboardReading协议,但使用它不会使实现更简单.
在NSPasteboard上复制字符串之前,最好清除内容然后保存.
斯威夫特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];
此外,还有其他可用类型用于在NSPasteboard上复制项目.喜欢:
NSPasteboardTypeString
NSPasteboardTypePDF
NSPasteboardTypeTIFF
NSPasteboardTypePNG
NSPasteboardTypeRTF
您可以在https://developer.apple.com/documentation/appkit/nspasteboardtype上找到更多详细信息.