Marci-man
Marci-man

Reputation: 2233

how to detect pasteboard item type

I am trying to identify between three types of objects:

  1. if it is a URL of a file
  2. If it is a URL of a directory
  3. if it is a simple string

up till now, I have just this code, which does not work!

NSArray * classes = nil;
            classes = [[NSArray alloc] initWithObjects:[NSURL class],
                       [NSAttributedString class],[NSString class], nil];

            NSDictionary *options = [NSDictionary dictionary];
            NSArray * copiedItems = nil;
            copiedItems = [pb readObjectsForClasses:classes options:options];

Now I try to take the first object of the array copiedItems and try to call "types" property and i get a crash!

Upvotes: 2

Views: 1043

Answers (2)

Merlevede
Merlevede

Reputation: 8170

Check here and here:
You would need to use these pasteboard types, instead of the ones you're using.

NSString *NSStringPboardType;
NSString *NSFilenamesPboardType;
NSString *NSPostScriptPboardType;
NSString *NSTIFFPboardType;
NSString *NSRTFPboardType;
NSString *NSTabularTextPboardType;
NSString *NSFontPboardType;
NSString *NSRulerPboardType;
NSString *NSFileContentsPboardType;
NSString *NSColorPboardType;
NSString *NSRTFDPboardType;
NSString *NSHTMLPboardType;
NSString *NSPICTPboardType;
NSString *NSURLPboardType;
NSString *NSPDFPboardType;
NSString *NSVCardPboardType;
NSString *NSFilesPromisePboardType;
NSString *NSMultipleTextSelectionPboardType;

There's an pasteboard type for URLs. To distinguish between a file and a folder, you would need to instantiate an NSURL object with the pasteboard data, and find out if it is a directory by querying its attributes.

EDIT: You also need to consider if the pasteboard data is being put there by your own application or other applications. If it's being put by other applications, I'm not sure the pasteboard types with the classes will work.

I use something like this in one of my projects:

supportedTypes = // array with supported types, maybe from the list
NSString *type = [pasteboard availableTypeFromArray:supportedTypes];
NSData *data = [pasteboard dataForType:type];

Upvotes: 3

Wain
Wain

Reputation: 119031

types is a method on NSPasteboard used to tell you what is available from the pasteboard. So, you shouldn't call it on the items you get back from the pasteboard.

If you're going to request multiple class types, iterate over the response and check the class type of each item, then decide how to interact with it.

Alternatively, decide which class type of data is most useful and make individual class type requests to the pasteboard. If you get a result back, use it and carry on, if not, try the next most useful class type. Look at using canReadObjectForClasses:options: to make this easier.

Upvotes: 0

Related Questions