我有一个不露面的 Mac OS X 应用程序,需要从其他应用程序复制选择。我通过模拟 CMD+C 击键来实现这一点。它工作完美。
但我认为有一个至关重要的副作用。它会在未经用户许可的情况下覆盖用户的粘贴板。
所以我想在复制选择之前我应该保存粘贴板内容然后恢复它。有人可以给我一些提示,也许是示例代码?
这里有一个类别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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)