将MacOS X菜单栏应用程序设置为在启动时启动

Laz*_*man 6 cocoa appstore-sandbox

我有一个沙盒菜单栏应用程序(没有停靠栏图标),在其首选项窗口中,用户可以选中一个复选框,让应用程序在登录时启动.我以前使用LSSharedFileList api,但由于沙盒应用程序不再允许这样做,我已迁移到使用SMLoginItemSetEnabled.我发现虽然应用程序将在登录时启动,但正如预期的那样,如果我回到首选项并取消选中并重新检查登录时的启动复选框,我会启动我的菜单栏应用程序的第二个实例.

这是我的帮助应用程序代码(在其app代理中):

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

    NSString * path = [[[[[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent]
                                    stringByDeletingLastPathComponent]
                                            stringByDeletingLastPathComponent]
                                                    stringByDeletingLastPathComponent];


    [[NSWorkspace sharedWorkspace] launchApplication:path];
    [NSApp terminate:nil];
Run Code Online (Sandbox Code Playgroud)

}

这是我的首选项窗口(主应用程序)中的代码:

- (IBAction)toggleLoginStatus:(NSButton*)sender{


    if(!SMLoginItemSetEnabled((__bridge CFStringRef)@"myAppBundleIdentifier", (BOOL)[sender state])){
            NSLog(@"Dagnabit!");
    }
Run Code Online (Sandbox Code Playgroud)

}

第二个实例启动后,取消选中/重新检查复选框不再启动实例.有谁知道发生了什么事?谢谢

Laz*_*man 2

我已经找到答案了。我看过的教程都没有提到这一点,但在 SMLoginItemEnabled 的文档中这样说:

帮助程序应用程序的布尔启用状态。该值仅对当前登录用户有效。如果为 true,则帮助程序应用程序将立即启动(并在后续登录时)并保持运行。如果为 false,则帮助程序应用程序将不再保持运行。

因此,在允许帮助程序启动应用程序之前,我必须检查应用程序是否已经在运行。