Multiple types on pasteboard including files, rtfd, and custom type (Mac OS X 10.6)
The new pasteboard api in 10.6 seems to work well once you 开发者_Go百科get your head around UTIs, but I've come across a situation that I can't crack: What if you're declaring multiple data types in conjunction with a file drag?
See the way the new pasteboard works, you put data on it using setString, setData, setPropertyList, or writeObjects. The first 3 require that you specify the UTI in advance so the receiver can select the representation it wants.
The last one - writeObjects - requires an array of NSPasteboardWriting compliant objects, such as the convenience class NSPasteboardItem.
The problem is that the Finder interprets any url added to the pasteboard as a literal url, so rather than dragging a file it creates a url to the file.
There is no way (that I can find) to create an NSPasteboardItem for a URL. That leaves this (from the header):
APPKIT_EXTERN NSString *NSFilenamesPboardType; //Deprecated
// Use -writeObjects: to write file URLs to the pasteboard
However, if you mix a URL with an NSPasteboard item the result doesn't work.
NSPasteboardItem *noteItem = [[[NSPasteboardItem alloc] init] autorelease];
[noteItem setString:theString forType:NSPasteboardTypeString];
//Here is the problem: you can only have one or the other, not both.
[pasteboard writeObjects:[NSArray arrayWithObjects:noteItem, nil]]; //A
[pasteboard writeObjects:[NSArray arrayWithObject:fileURL]]; //B
// A or B will work but not both
[pasteboard writeObjects:[NSArray arrayWithObjects:
fileURL, noteItem, nil]]; //Will not work
I would consider it a great example if someone could write something that would accomplish both of these together.
Here is the test:
Drag to TextEdit should insert text
Drag to Finder should add a file.
writeObjects: is not the only method. You can also use:
- setData:forType:
- setPropertyList:forType:
- setString:forType:
For NSURL
you also have the opportunity to use the NSURL Additions (+URLFromPasteboard:
and -writeToPasteboard:
).
精彩评论