How to save off the pasteboard contents first and restore them afterward?

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-05 18:09:53

问题


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?


回答1:


Here's a category on NSPasteboard that I wrote to do this. It seems to work pretty well.

@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



回答2:


Look at NSPasteboard.

+[NSPasteboard generalPasteboard] will give you the shared pasteboard and you can use that class to get and set the contents.




回答3:


Alternative self-contained implementation using object associations:

#import <objc/runtime.h>

static void * kArchiveKey = &kArchiveKey;

@implementation NSPasteboard (SaveRestore)

- (void)setArchive:(NSArray *)newArchive
{
    objc_setAssociatedObject(self, kArchiveKey, newArchive, OBJC_ASSOCIATION_RETAIN);
}

- (NSArray *)archive
{
    return objc_getAssociatedObject(self, kArchiveKey);
}

- (void)save
{
    NSMutableArray *archive = [NSMutableArray array];
    for (NSPasteboardItem *item in [self pasteboardItems]) {
        NSPasteboardItem *archivedItem = [[NSPasteboardItem alloc] init];
        for (NSString *type in [item types]) {
            NSData *data = [item dataForType:type];
            if (data) {
                [archivedItem setData:data forType:type];
            }
        }
        [archive addObject:archivedItem];
    }
    [self setArchive:archive];
}

- (void)restore
{
    [self clearContents];
    [self writeObjects:[self archive]];
}

@end


来源:https://stackoverflow.com/questions/6118435/how-to-save-off-the-pasteboard-contents-first-and-restore-them-afterward

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!