0

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];
}
hugo411
  • 320
  • 1
  • 12
  • 29
  • Did you try anything to get all objects? – Willeke Aug 01 '18 at 21:15
  • nope, no docs at all and apple website is not helping. Why do you think i am here? – hugo411 Aug 14 '18 at 18:02
  • [NSPasteboard](https://developer.apple.com/documentation/appkit/nspasteboard?language=objc). Get `types`, read data: `dataForType:`, write data `setData:forType:`. Promises will be a problem. Hidden in the archives: [Pasteboard Programming Guide](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/PasteboardGuide106/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008100-SW1). – Willeke Aug 14 '18 at 22:36
  • thanks, i found a solution after being lucky and it is like you said. – hugo411 Aug 15 '18 at 13:55

1 Answers1

1

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).

hugo411
  • 320
  • 1
  • 12
  • 29