开发者

Copying a file to the clipboard

guys! Does anybody know how to achieve this? I mean: if I want to put a string to the clipboard I do

NSPasteboard *pboard = [NSPasteboard generalPasteboard];
[pboard declareTypes:[NSArray arrayWithObject:NSPasteboardTypeString] owner:self];
[pboard setString:@"aString" forType:NSPasteboardTypeString];

but what if I want to put a file into the cl开发者_JS百科ipboard? I'd like to find a way to use a filepath as a parameter and then being able to paste that file wherever I want in the Finder, via contextual menu or CMD-V.

Can anybody help me?

Thanks a lot!


After HOURS AND HOURS AND HOURS of searching around, I finally got a short answer...

NSArray *fileList = [NSArray arrayWithObjects:filePath1, filePath2, nil];
NSPasteboard *pboard = [NSPasteboard generalPasteboard];
[pboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil];
[pboard setPropertyList:fileList forType:NSFilenamesPboardType];


Put this together quickly, but is tested using both CMD+V and Contextual Paste.

NSURL *object = [[NSURL alloc] initFileURLWithPath:@"/Users/username/Desktop/main.png"];
NSPasteboard *pb = [NSPasteboard generalPasteboard];
[pb clearContents];

NSArray *objectsToCopy = [[NSArray alloc] initWithObjects:object, nil];
BOOL pasted = [pb writeObjects:objectsToCopy];

if(pasted) // paste was successful
    NSLog(@"pasted");

[object release];
[objectsToCopy release];
[pb release];


I haven't tried this but as I understand the documentation, all you have to do (at least in OS X 10.6+) is this:

NSURL *fileURL = [NSURL fileURLWithString:...];
NSPasteboard *pasteboard = [NSPasteboard generalPasteboard];
[pasteboard writeObjects:[NSArray arrayWithObject:fileURL]];

And to read the URL from the pasteboard:

NSArray *urls = [pasteboard readObjectsForClasses:[NSArray arrayWithObject[NSURL class]]
                                          options:[NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:NSPasteboardURLReadingFileURLsOnlyKey]];
if ([urls count] == 1) {
    NSURL *myFileURL = [urls objectAtIndex:0];
    ...
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜