Search code examples
objective-cmacosclipboardnspasteboard

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. I am only doing this with the text attribute right now. 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];
}

Solution

  • The easiest way i found is to get the array of all 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

    Then, you can write back to the pasteboard after your clipboard manipulations with that same array : [pasteboard writeObjects:arrayPasteboardItems];

    This will put back whatever object copied before (even files, folder, etc).