使用Objective-C/Cocoa启动Mac应用程序

8

当通过命令行启动Path Finder应用程序时,我使用open -a Path Finder.app /Users/命令。

基于这个想法,我使用下面的代码来启动Path Finder。

我能否在不使用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];
2个回答

28
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];

1
你需要使用launchApplicationAtURL:options:configuration:error:来实现这个。我会在我的帖子中添加一个使用它的例子。 - ughoavgfhw
嗯,我不确定,但从简洁性方面来看,我的答案(使用 openFile: withApplication:)似乎更好(更易于理解和更短)。 - prosseek
我如何访问已打开应用程序中的配置字典? - rocky
2
@rocky 你不能直接访问字典,但是存储在字典中的参数将作为命令行参数传递,因此你可以在主函数中使用 argcargv - ughoavgfhw
@ughoavgfhw 哪一个会更快? - PR Singh

3
基于yuji在不同的帖子中的答案,NSWorkspace是要使用的工具,我只需两行代码就可以得到相同的结果。 openFile可用于将参数传递给Path Finder,通常是目录而不是文件。但它可以正常工作。
[[NSWorkspace sharedWorkspace] openFile:string2 withApplication:@"Path Finder"];
[[NSApplication sharedApplication] terminate:nil];

1
如果_parameter_不是文件而是应用程序的参数,那么这将无法工作。 - Shebuka

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