Launching a Mac application using Objective-C / Cocoa

When I run the Path Finder command-line application, I use open -a Path Finder.app /Users/ . Based on this idea, I use the following code to run the Path Finder.

Can I run the application without using the open command line?

 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]; 
+8
objective-c cocoa
source share
2 answers
 if(![[NSWorkspace sharedWorkspace] launchApplication:@"Path Finder"]) NSLog(@"Path Finder failed to launch"); 

With parameters:

 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 

You can also use NSTask to pass arguments:

 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]; 
+24
source share

Based on yuji's answer in various publications , NSWorkspace is a tool to use, and I could get the same result with only two lines of code.

openFile can be used to pass the Path Finder parameter, which is usually a directory, not a file. However, it works great.

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

All Articles