Mac GUI应用程序如何在不使用Sparkle的情况下重新启动自己?

How can a Mac GUI app relaunch itself without using Sparkle?

本文关键字:Sparkle 情况下 重新启动 自己 应用程序 GUI Mac      更新时间:2023-10-16

我正在给Mac程序添加一个功能,删除它的preferences .plist文件,然后用有效的"出厂设置"重新启动。然而,这方面的客户对使用像Sparkle这样的外部框架持怀疑态度。我在网上找了一些示例代码,但其中大部分似乎过于复杂(例如,在NSApplication中添加一个类别)。此外,当你不能使用一些api从非GUI进程启动GUI进程时,其中一些在Lion或更高版本中根本无法工作。

那么是否有一种简单的方法可以让Mac GUI应用程序重新启动?

至少对于Mountain Lion来说,fork/exec的一个稍微花哨的版本工作得很好:

void    RelaunchCurrentApp()
{
    // Get the path to the current running app executable
    NSBundle* mainBundle = [NSBundle mainBundle];
    NSString* executablePath = [mainBundle executablePath];
    const char* execPtr = [executablePath UTF8String];
#if ATEXIT_HANDLING_NEEDED
    // Get the pid of the parent process
    pid_t originalParentPid = getpid();
    // Fork a child process
    pid_t pid = fork();
    if (pid != 0) // Parent process - exit so atexit() is called
    {
        exit(0);
    }
    // Now in the child process
    // Wait for the parent to die. When it does, the parent pid changes.
    while (getppid() == originalParentPid)
    {
        usleep(250 * 1000); // Wait .25 second
    }
#endif
    // Do the relaunch
    execl(execPtr, execPtr, NULL);
}

我遇到了一个问题,那就是重新启动的应用程序可能会在后台结束。在执行早期这样做可以修复这个问题:

[[NSApplication sharedApplication] activateIgnoringOtherApps : YES];