如何在Objective-C应用程序中退出自身?

11

我有一个URLHandler,它启动了某个应用程序,主要代码如下。

@implementation URLHandlerCommand

- (id)performDefaultImplementation {
    NSString *urlString = [self directParameter];

    NSLog(@"url :=: %@", urlString);

    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/open"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects: @"-a", @"Path Finder.app", urlString, nil];
    [task setArguments: arguments];

    NSPipe *pipe;
    pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    return nil;
}

由于此程序的目标是启动另一个应用程序,因此我想在启动应用程序后使该URLHandler退出。 我该如何做到这一点?

2个回答

19
  1. 你不需要使用NSTask来启动open... open只是调用Launch Services,其中一些功能可以直接从NSWorkspace使用。

  2. 要退出,只需调用[[NSApplication sharedApplication] terminate:nil]。详见NSApplication文档


2
谢谢您的回答,看来exit(0)运行良好。 - prosseek
3
我不建议使用 exit(0)。Cocoa 在退出前可能需要进行一些清理工作。我不确定 Cocoa 是否将这些清理函数注册到 atexit 中,因此我建议您调用 -[NSApplication terminate:] - Yuji

1

这个问题已经在这里得到了回答:正确的退出iPhone应用程序的方法是什么?,但你也应该看一下August的回答。虽然它不是被接受的答案,但它得到了更高的投票,并且也遵循了苹果的标准,因为苹果建议不要强制退出iPhone应用程序。


1
实际上,这是一个Mac应用程序,而不是iPhone应用程序。 - prosseek
啊,我明白了。很抱歉我做出了假设。 - aiham

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接