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

daf*_*afi 3 cocoa pasteboard osx-snow-leopard

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

我编写了符合Snow Leopard准则的下面显示的代码(例如,在复制文件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"];
// 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];
Run Code Online (Sandbox Code Playgroud)

但是在一些编辑器(如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
Run Code Online (Sandbox Code Playgroud)

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

NSFilenamesPboardType用法似乎气馁

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

Jon*_*an. 5

文档可能听起来只能使用writeObjects:,但您只能将其用于文件URL.

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

APPKIT_EXTERN NSString *NSStringPboardType;     // Use NSPasteboardTypeString
APPKIT_EXTERN NSString *NSFilenamesPboardType;      // Use -writeObjects: to write file URLs to the pasteboard
Run Code Online (Sandbox Code Playgroud)

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

所以要获得正确的行为:

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];
Run Code Online (Sandbox Code Playgroud)