-[NSWorkspace openApplicationAtURL:configuration:completionHandler:] 在登录项中不起作用

-[NSWorkspace openApplicationAtURL:configuration:completionHandler:] does not work in login item

在我的 MacOS 应用程序中有一个使用 -[NSWorkspace launchApplicationAtURL:options:configuration:error:] 方法启动主应用程序的登录项。它工作正常,但现在已弃用此方法,取而代之的是 -[NSWorkspace openApplicationAtURL:configuration:completionHandler:]。当我尝试使用后者时,没有任何反应。没有启动任何应用程序,也没有报告任何错误。此处为原代码,略去小细节

int main() {
  @autoreleasepool {
    NSBundle* bundle = NSBundle.mainBundle;
    NSWorkspace* workspace = NSWorkspace.sharedWorkspace;

    NSString* path = bundle.bundlePath;
    for (int i = 0; i < 4; ++i) {
      path = [path stringByDeletingLastPathComponent];
    }

    NSDictionary* env = @{
//      ...
    };
    
#if 1 /* switch between new and old method versions */
    NSWorkspaceOpenConfiguration* configuration = [NSWorkspaceOpenConfiguration new];
    [configuration setEnvironment: env];
    [configuration setPromptsUserIfNeeded: YES];
    [workspace openApplicationAtURL: [NSURL fileURLWithPath: path] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {
      if (error) {
        NSLog(@"Failed to run the app: %@", error.localizedDescription);
      }
    }];
#else
    NSDictionary* configuration = @{ NSWorkspaceLaunchConfigurationEnvironment: env };

    NSError* error = nil;
    [workspace launchApplicationAtURL: [NSURL fileURLWithPath: path]
                              options: NSWorkspaceLaunchDefault
                        configuration: configuration
                                error: &error];

    if (error) {
      NSLog(@"Failed to run the app: %@", error.localizedDescription);
    }
#endif
  }
  return 0;
}

有没有人有类似的问题?我在使用新方法时做错了什么?

想通了。登录项退出得太早。它应该等待打开操作完成。类似于:

    [workspace openApplicationAtURL: [NSURL fileURLWithPath: path] configuration: configuration completionHandler:^(NSRunningApplication* app, NSError* error) {
      if (error) {
        NSLog(@"Failed to run the app: %@", error.localizedDescription);
      }
      exit(0);
    }];
    [NSThread sleepForTimeInterval: 10];