简体   繁体   English

为什么在应用程序已运行时未调用application:openFile :?

[英]Why isn't application:openFile: called when the application is already running?

I would like to handle open events when a user double-clicks on a file that was created by my application, or drags such a file onto the dock icon. 当用户双击由我的应用程序创建的文件,或将此类文件拖到停靠图标时,我想处理打开事件。

I've therefore implemented NSApplicationDelegate 's application:openFile: and application:openFiles: methods, which work as expected when the application is not running. 因此,我已经实现了NSApplicationDelegateapplication:openFile:application:openFiles:方法,这些方法在应用程序未运行时可以按预期工作。

However, if the application is already running when the open event occurs, the application becomes focused, but the above methods are never called (breakpoints inside them are not hit) and the files do not open. 但是,如果在打开事件发生时应用程序已经在运行,则该应用程序将变为焦点,但不会调用上述方法(不会击中它们内部的断点),并且文件也不会打开。

I also tried implementing application:openURLs: . 我也尝试实现application:openURLs: This method has the same behaviour: it is not called if the application is already running when the event occurs. 此方法具有相同的行为:事件发生时,如果应用程序已在运行,则不会调用该方法。

Do I need to implement different functions to handle opening files when the application is already running, or is there something else I need to do/set in order for the existing functions to be called in those circumstances? 在应用程序已经运行时,我是否需要实现不同的功能来处理打开文件,还是需要做/设置其他事情以便在这种情况下调用现有功能?

This is not mentioned in the documentation , but according to this answer the way that application:openFile: works is that it NSApplication forwards odoc Apple Events to its delegate. 文档中未提及,但根据此答案application:openFile:工作方式是NSApplicationodoc Apple Events转发给其委托。

Armed with this knowledge, I was able to find the following old Carbon call in the app: 有了这些知识,我就可以在应用程序中找到以下旧的Carbon通话:

osError = AEInstallEventHandler(kCoreEventClass,
                                kAEOpenDocuments,
                                g_OpenDocumentsUPP,
                                0L,
                                false);

I'm presuming this existing event handler consumed the Apple Event before NSApplication had a chance to deal with it. 我假设这个现有的事件处理程序在NSApplication有机会处理它之前就消耗了Apple Event。 However, when the app is not already running, NSApplication handles the event before the line above setting up the event handler is called, hence the different behaviour. 但是,当应用程序尚未运行时, NSApplication将在设置事件处理程序的上述行被调用之前处理事件,因此行为有所不同。

Removing this old code from the build caused the NSApplicationDelegate methods to be called, thus fixing the issue. 从构建中删除此旧代码会导致调用NSApplicationDelegate方法,从而解决了该问题。

Does the following method work? 以下方法有效吗?

- (void)application:(NSApplication *)application 
       openURLs:(NSArray<NSURL *> *)urls;

If your delegate implements this method, AppKit does not call the
application:openFile: or application:openFiles: methods.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM