How to pass parameters between cocoa applications

I have a Cocoa application (.app) and I would like to launch it from another Cocoa application, no problem here, but is there a way to start a second application passing some parameters to it? perhaps using the argv [] array in the main function?


source to share

2 answers

I did this using NSWorkspace to launch the application and NSDistributedNotificationCenter to transfer the data. This is clearly not fully developed, but it worked. One caveat from the docs - the dictionary I sent with an argument (just a string in this example) cannot be used in a sandboxed application (the dictionary must be zero).

This is the app that opens another app:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
ws = [NSWorkspace sharedWorkspace];
NSNotificationCenter *center = [ws notificationCenter];
[center addObserver:self selector:@selector(poster:) name:NSWorkspaceDidLaunchApplicationNotification object:nil];
[ws launchApplication:@""];



-(void)poster:(NSNotification *) aNote {
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
NSDictionary *dict = [NSDictionary dictionaryWithObject:@"theDataToSend" forKey:@"startup"];
[center postNotificationName:@"launchWithData" object:nil userInfo:dict];
NSLog(@"Posted notification");



And this is in the opened application:

-(void)awakeFromNib {
NSDistributedNotificationCenter *center = [NSDistributedNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(doStartup:) name:@"launchWithData" object:nil];



-(void)doStartup:(NSNotification *) aNote {





How do you launch the second Cocoa app?

When I have done this, I usually communicate with another application via AppleScript via NSAppleScript

. You can also launch applications. Of course, the other application must support AppleScript.

You can also use distributed objects if you have control over both applications, but it is more complex.

If you have ever had to work with a program from the command line, then it is useful to use NSTask




All Articles