IamInTrouble
IamInTrouble

Reputation: 67

Copy the complete content of general NSPasteboard

I need to copy the complete content of general NSPasteboard to a pasteboard with specified name. I tried this code:

- (void)copyFromGeneralPasteboard {
NSMutableArray *archive = [[NSMutableArray alloc] init];
NSArray *typeArray = [[NSPasteboard generalPasteboard] types];
NSPasteboard *myPasteboard = [NSPasteboard pasteboardWithName:@"SpecialPb"];
[myPasteboard declareTypes:typeArray owner:self];

for (NSPasteboardItem *item in [[NSPasteboard generalPasteboard] pasteboardItems])
{
    NSPasteboardItem *archivedItem = [[NSPasteboardItem alloc] init];
    for (NSString *type in [item types])
    {
        NSData *data=[[item dataForType:type] mutableCopy];
        if (data) {
            [archivedItem setData:data forType:type];
        }
    }
    [archive addObject:archivedItem];
}
[[NSPasteboard generalPasteboard] clearContents];
[myPasteboard writeObjects:archive];
[archive removeAllObjects];}

and I am using this code to check.

- (void)SendToGeneralPasteboard {
NSMutableArray *archive = [[NSMutableArray alloc] init];
for (NSPasteboardItem *item in [[NSPasteboard pasteboardWithName:@"SpecialPb"] pasteboardItems])
{
    NSPasteboardItem *archivedItem = [[NSPasteboardItem alloc] init];
    for (NSString *type in [item types])
    {
        NSData *data=[[item dataForType:type] mutableCopy];
        if (data) {
            [archivedItem setData:data forType:type];
        }
    }
    [archive addObject:archivedItem];
}
[[NSPasteboard generalPasteboard] writeObjects:archive];}

So, I performed a test using IWork Pages and it works with text and attributed text. But, when I tried to run with text and image, the program just copy and paste the text. Besides, I tried to run using just image, it woks too. Could you tell me how can I use my code with any type of data? Thanks.

Upvotes: 0

Views: 808

Answers (1)

danielpunkass
danielpunkass

Reputation: 17587

I realize this is an old question, but I was working with similar stuff today so I thought I'd answer this in case anybody else is looking.

Since you're just trying to copy the complete contents from one pasteboard to another, there's no need to mess around with NSPasteboardItem. Just iterate all the typed data in one pasteboard and write it to another. Concise example in Swift:

func copyItemsFromPasteboard(_ fromPasteboard: NSPasteboard, toPasteboard: NSPasteboard) {
    for thisType in fromPasteboard.types ?? [] {
        let thisData = fromPasteboard.data(forType: thisType) ?? Data()
        toPasteboard.setData(thisData, forType: thisType)
    }
}

let generalPB = NSPasteboard(name: .generalPboard)
let customPB = NSPasteboard(name: NSPasteboard.Name(rawValue: "com.example.custom"))

copyItemsFromPasteboard(generalPB, toPasteboard: customPB)

I hope this helps somebody!

Upvotes: 4

Related Questions