8

使用命令行启动路径查找器应用程序时,我使用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];
4

2 回答 2

27
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];
于 2011-02-19T05:01:42.177 回答
3

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

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

[[NSWorkspace sharedWorkspace] openFile:string2 withApplication:@"Path Finder"];
[[NSApplication sharedApplication] terminate:nil];
于 2011-02-19T05:00:15.550 回答