简体   繁体   English

从NSPasteboard Mac获取剪贴板的对象

[英]Obtain clipboard's object from NSPasteboard mac

i need to obtain the NSPasteboard's object and store it somewhere in order to put it back to the clipboard later. 我需要获取NSPasteboard的对象并将其存储在某处,以便稍后将其放回剪贴板。 I am only doing this with the text attribute right now. 我现在仅使用text属性来执行此操作。 I want to know how to do this with any object (example : copy a file). 我想知道如何对任何对象执行此操作(例如:复制文件)。 Here is my code so far for getting the text and putting it back : 到目前为止,这是我获取代码并将其放回原处的代码:

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];
}

The easiest way i found is to get the array of all NSPasteboardItems : 我找到的最简单的方法是获取所有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;
}

from this page : Dissociating NSPasteboardItem from pasteboard 来自此页面:将NSPasteboardItem与粘贴板分离

Then, you can write back to the pasteboard after your clipboard manipulations with that same array : [pasteboard writeObjects:arrayPasteboardItems]; 然后,您可以在剪贴板操作之后使用相同的数组写回粘贴板: [pasteboard writeObjects:arrayPasteboardItems];

This will put back whatever object copied before (even files, folder, etc). 这将放回之前复制的所有对象(甚至文件,文件夹等)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM