复制到Snow Leopard或更高版本的粘贴板文件路径和URL

时间:2012-02-26 16:09:14

标签: cocoa osx-snow-leopard pasteboard

我想在剪贴板中复制文件路径,以便将它们作为字符串复制到文本编辑器中,但我希望它们也可供Finder复制文件。

我编写了符合Snow Leopard准则的下面显示的代码(例如,在复制文件网址时使用writeObjects)

NSString* path1 = @"/Users/dave/trash/mas.sh";
NSString* path2 = @"/Users/dave/trash/books.xml";
NSURL* url1 = [NSURL fileURLWithPath:path1 isDirectory:NO];
NSURL* url2 = [NSURL fileURLWithPath:path2 isDirectory:NO];
NSArray* paths = [NSArray arrayWithObjects:path1, path2, nil];

NSString* pathPerLine = [paths componentsJoinedByString:@"\n"];
// Put strings on top otherwise paster app receives the url (only the first)
// Urls will be used by Finder for files operations (copy, move)
NSArray* urls = [NSArray arrayWithObjects:pathPerLine, url1, url2, nil];
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard writeObjects:urls];

但是在某些编辑器(如XCode)上也会粘贴网址,如下所示(Finder正确使用网址进行复制/移动)

/Users/dave/trash/mas.sh
/Users/dave/trash/books.xml
file://localhost/Users/dave/trash/mas.sh
file://localhost/Users/dave/trash/books.xml

如何使用符合10.6标准的代码仅粘贴没有文件URL的文件路径?

NSFilenamesPboardType使用似乎不鼓励

  

NSFilenamesPboardType       指定一个或多个文件名的NSString对象数组。       在Mac OS X v10.6及更高版本中,使用writeObjects:将文件URL写入粘贴板。       适用于Mac OS X v10.0及更高版本。       在NSPasteboard.h中声明。

1 个答案:

答案 0 :(得分:5)

文档可能听起来只能使用writeObjects:,但您只能将其用于文件网址。

在NSPasteboard.h的底部是这一部分:

APPKIT_EXTERN NSString *NSStringPboardType;     // Use NSPasteboardTypeString
APPKIT_EXTERN NSString *NSFilenamesPboardType;      // Use -writeObjects: to write file URLs to the pasteboard

这些是您不应使用的旧类型,但它表明您在尝试放置文件URL(或URL)时仅使用writeObjects:。并使用其他数据的类型。

所以要获得正确的行为:

NSString* path1 = @"/Users/dave/trash/mas.sh";
NSString* path2 = @"/Users/dave/trash/books.xml";
NSURL* url1 = [NSURL fileURLWithPath:path1 isDirectory:NO];
NSURL* url2 = [NSURL fileURLWithPath:path2 isDirectory:NO];
NSArray* paths = [NSArray arrayWithObjects:path1, path2, nil];

NSString* pathPerLine = [paths componentsJoinedByString:@"\n"];

//Note, only the URLs not the pathsPerLine
NSArray* urls = [NSArray arrayWithObjects:url1, url2, nil];
NSPasteboard* pasteboard = [NSPasteboard generalPasteboard];
[pasteboard clearContents];
[pasteboard writeObjects:urls];
//Now add the pathsPerLine as a string
[pasteboard setString:pathPerLine forType:NSStringPboardType];