从 NSPasteboard 获取剪贴板的对象 mac

Obtain clipboard's object from NSPasteboard mac

我需要获取 NSPasteboard 的对象并将其存储在某个地方,以便稍后将其放回剪贴板。我现在只对文本属性执行此操作。我想知道如何对任何对象执行此操作(例如:复制文件)。 到目前为止,这是我获取文本并将其放回的代码:

NSString *pasteboardString;

//Save the value of the pasteboard
NSPasteboard *pasteboard= [NSPasteboard generalPasteboard];
pasteboardString= [pasteboard stringForType:NSStringPboardType];

//Clear the pasteboard
[pasteboard clearContents];

//Do some stuff with clipboard

//Write the old object back
if(pasteboardString!= NULL || pasteboardString.length != 0){
    [pasteboard declareTypes:[NSArray arrayWithObject:NSStringPboardType] owner:nil];
    [pasteboard setString:pasteboardString forType:NSStringPboardType];
}

我找到的最简单的方法是获取所有 NSPasteboardItems 的数组:

- (NSArray *)readFromPasteBoard
{
    NSMutableArray *pasteboardItems = [NSMutableArray array];
    for (NSPasteboardItem *item in [pasteboard pasteboardItems]) {
        //Create new data holder
        NSPasteboardItem *dataHolder = [[NSPasteboardItem alloc] init];
        //For each type in the pasteboard's items
        for (NSString *type in [item types]) {
            //Get each type's data and add it to the new dataholder
            NSData *data = [[item dataForType:type] mutableCopy];
            if (data) {
                [dataHolder setData:data forType:type];
            }
        }
        [pasteboardItems addObject:dataHolder];
    }
    return pasteboardItems;
}

来自此页面:Dissociating NSPasteboardItem from pasteboard

然后,您可以在对同一数组进行剪贴板操作后写回粘贴板:[pasteboard writeObjects:arrayPasteboardItems];

这将放回之前复制的任何对象(甚至文件、文件夹等)。