为什么NSApplicationDelegate方法openFiles:多次拖动到停靠图标时被多次调用?

Alf*_*uro 6 xcode cocoa objective-c nsapplication nsapplication-delegate

我有一个Mac OS X应用程序,它实现了 - (void)应用程序openFiles:方法来响应应用程序图标上的拖动文件.我在目标信息设置的文档类型部分中有一个允许的文件类型列表,Finder确实允许拖动,但是当pdf在拖动项目列表中时,我的委托方法被调用两次:一个用于所有元素而没有pdf,仅用于PDF.这当然使我无法正确处理这种情况.任何人都可以帮助我或解释发生了什么?谢谢

zpa*_*ack 8

我在我的一个应用程序中看到过这种行为(通常在同时拖动一大堆文件时).当我解决方法时,不是直接打开文件,而是将application:openFiles:它们排队并在一小段延迟后打开排队的文件.类似于以下内容:

- (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];
}
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢zpasternack!然而奇怪的行为! (2认同)
  • 绝对荒谬的行为。我自己遇到了麻烦。 (2认同)
  • 我建议使用非重复的 `NSTimer` 而不是 `-performSelector:withObject:afterDelay`,因为您可以在后续的 `-application:openFiles:` 调用中取消计时器以重置打开的排队文件延迟。这样你的 `-openQueuedFiles` 调用只会在你的计时器延迟时间范围内调用一次。 (2认同)