Question

I want to copy file paths in clipboard so they can be copied in text editors as strings but I want them also available to Finder to copy files.

I've written the code shown below compliant with Snow Leopard guidelines (eg use writeObjects when copy file urls)

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

But on some editors (like XCode) also the urls are pasted as shown below (Finder uses correctly the urls to copy/move)

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

How can I paste only the file paths without the file URLs using 10.6 compliant code?

The NSFilenamesPboardType usage seems discouraged

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.

Was it helpful?

Solution

The documentation can sound like you must only use writeObjects:, but you only use this for the file URLs.

At the bottom of NSPasteboard.h is this section:

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

These are the old types you shouldn't use but it shows that you only use writeObjects: when trying to put file URLs (or URLs). And use the types for other data.

So to get the correct behaviour:

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top