Why NSApplicationDelegate method openFiles: is being called multiple times on a multiple drag to the dock icon?
Asked Answered
F

1

7

I have a Mac OS X application that implements the -(void)application openFiles: method to react to dragged files on the application icon.

I have a list of allowed filetypes in the document types section of my target info settings and the Finder indeed allows drags, but when a PDF is in the list of dragged items, my delegate method is called twice: one for all the elements without the PDF, and one for the PDF alone.

This of course makes it impossible for me to handle the situation properly.

Can anybody help me or explain what is happening? Thanks

Febrile answered 3/6, 2016 at 21:29 Comment(1)
Possible duplicate of Application:openFiles: separate files by groupsImphal
D
11

I've seen this behavior in one of my apps (usually when dragging a whole bunch of files at one time). As I workaround, instead of opening the files directly from application:openFiles:, I queue them up and open the queued files after a small delay. Something like the following:

- (void) application:(NSApplication*)sender openFiles:(NSArray*)filenames
{
    // I saw cases in which dragging a bunch of files onto the app
    // actually called application:openFiles several times, resulting
    // in more than one window, with the dragged files split amongst them.
    // This is lame.  So we queue them up and open them all at once later.
    [self queueFilesForOpening:filenames];

    [NSApp replyToOpenOrPrint:NSApplicationDelegateReplySuccess];
}


- (void) queueFilesForOpening:(NSArray*)filenames
{
    [self.filesToOpen addObjectsFromArray:filenames];
    [self performSelector:@selector(openQueuedFiles) withObject:nil afterDelay:0.25];
}


- (void) openQueuedFiles
{
    if( self.filesToOpen.count == 0 ) return;

    [self makeNewWindowWithFiles:self.filesToOpen];

    [self.filesToOpen removeAllObjects];
}
Dubuffet answered 4/6, 2016 at 1:18 Comment(5)
Thanks a lot zpasternack ! strange behaviour however !Febrile
Absolutely ridiculous behaviour. Having trouble with this myself.Horsewoman
Me too. I only get it for the first file I try to import. Any subsequent imports just issue the single call.Mcallister
FWIW, I used a similar approach but with a NSMutableSet to automatically remove duplicates.Mcallister
I'd recommend using a non-repeating NSTimer instead of -performSelector:withObject:afterDelay because you can cancel the timer on subsequent -application:openFiles: calls to reset the open queued files delay. This way your -openQueuedFiles call is only called once inside your timer delay timeframe.Fruitful

© 2022 - 2024 — McMap. All rights reserved.