gpt4 book ai didi

cocoa - 在 Snow Leopard 或更高版本上复制到粘贴板文件路径和 URL

转载 作者:行者123 更新时间:2023-12-03 16:18:00 25 4
gpt4 key购买 nike

我想复制剪贴板中的文件路径,以便可以将它们作为字符串复制到文本编辑器中,但我希望 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];

但在某些编辑器(如 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 An array of NSString objects designating one or more filenames. On Mac OS X v10.6 and later, use writeObjects: to write file URLs to the pasteboard. Available in Mac OS X v10.0 and later. Declared in NSPasteboard.h.

最佳答案

文档听起来好像您必须只使用 writeObjects:,但您只能将其用于文件 URL。

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];

关于cocoa - 在 Snow Leopard 或更高版本上复制到粘贴板文件路径和 URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9454638/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com