如何先保存粘贴板内容,然后恢复? [英] How to save off the pasteboard contents first and restore them afterward?
本文介绍了如何先保存粘贴板内容,然后恢复?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个匿名的Mac OS X应用程序,需要从其他应用程序复制选择。我通过模拟CMD + C键击实现这一点。它工作完美。
但是有一个,我觉得很关键,副作用。它会覆盖用户的粘贴板没有他们的权限。
所以我在想我之前复制选择我应该保存粘贴板内容,然后恢复。有人可以给我一些提示,也许示例代码?
I have a faceless Mac OS X app which needs to copy selection from other apps. I achieve this by simulating CMD+C keystrokes. It works perfectly. But there is a, I think it's critical, side effect. It'll override users' pasteboard without their permission. So I was thinking before I copying selection I should save pasteboard content and then restore it. Can someone give me some hint, maybe sample code?
推荐答案
这是一个类别 NSPasteboard
@implementation NSPasteboard (SaveAndRestore)
// save current contents as an array of pasteboard items
- (NSArray *)save
{
NSMutableArray *archive=[NSMutableArray array];
for (NSPasteboardItem *item in [self pasteboardItems])
{
NSPasteboardItem *archivedItem=[[NSPasteboardItem alloc] init];
for (NSString *type in [item types])
{
/* The mutableCopy performs a deep copy of the data. This avoids
memory leak issues (bug in Cocoa?), which you might run into if
you don't copy the data. */
NSData *data=[[item dataForType:type] mutableCopy];
if (data) { // nil safety check
[archivedItem setData:data forType:type];
}
}
[archive addObject:archivedItem];
}
return archive;
}
// restore previously saved data
- (void)restore:(NSArray *)archive
{
[self clearContents];
[self writeObjects:archive];
}
@end
这篇关于如何先保存粘贴板内容,然后恢复?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文