【问题标题】:Launching an Mac App with Objective-C/Cocoa使用 Objective-C/Cocoa 启动 Mac 应用程序
【发布时间】:2011-02-19 03:35:38
【问题描述】:

使用命令行启动路径查找器应用程序时,我使用open -a Path Finder.app /Users/。 基于这个想法,我使用下面的代码来启动路径查找器。

我可以在不使用open 命令行的情况下启动应用程序吗?

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

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

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

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

【问题讨论】:

    标签: objective-c cocoa launching-application


    【解决方案1】:
    if(![[NSWorkspace sharedWorkspace] launchApplication:@"Path Finder"])
        NSLog(@"Path Finder failed to launch");
    

    带参数:

    NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
    NSURL *url = [NSURL fileURLWithPath:[workspace fullPathForApplication:@"Path Finder"]];
    //Handle url==nil
    NSError *error = nil;
    NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
    [workspace launchApplicationAtURL:url options:0 configuration:[NSDictionary dictionaryWithObject:arguments forKey:NSWorkspaceLaunchConfigurationArguments] error:&error];
    //Handle error
    

    你也可以使用 NSTask 来传递参数:

    NSTask *task = [[NSTask alloc] init];
    NSBundle *bundle = [NSBundle bundleWithPath:[[NSWorkspace sharedWorkspace] fullPathForApplication:@"Path Finder"]]];
    [task setLaunchPath:[bundle executablePath]];
    NSArray *arguments = [NSArray arrayWithObjects:@"Argument1", @"Argument2", nil];
    [task setArguments:arguments];
    [task launch];
    

    【讨论】:

    • 您需要使用 launchApplicationAtURL:options:configuration:error: 来执行此操作。我将在我的帖子中添加一个使用它的示例。
    • 好吧,我不确定,但就简洁而言,我的答案(使用 openFile: withApplication:) 似乎更好(更容易理解且更短)。
    • 如何在打开的应用中访问配置字典?
    • @rocky 你不能直接访问字典,但是字典中存储的参数会作为命令行参数传递,所以你可以在主函数中使用argcargv。跨度>
    • @ughoavgfhw 哪个会快?
    【解决方案2】:

    根据 yuji 在different posting 中的回答,NSWorkspace 是要使用的工具,我只需两行代码就可以得到相同的结果。

    openFile 可用于将参数传递给Path Finder,通常是目录,而不是文件。但是,它工作正常。

    [[NSWorkspace sharedWorkspace] openFile:string2 withApplication:@"Path Finder"];
    [[NSApplication sharedApplication] terminate:nil];
    

    【讨论】:

    • 这行不通,因为 parameter 不是文件,而是应用程序的 parameter
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多