views:

506

answers:

2

I'm trying to run an applescript inside my Cocoa app using the system(); function - the string I'm passing to the function works in terminal and the applescript itself is fine, I think it has something to do with NSString - can anyone help?

  //add to login items
  NSLog(@"add to login");
  NSString *pathOfApp = [[NSBundle mainBundle] bundlePath];
  NSString *theASCommandLoginItem = [NSString stringWithFormat:@"/usr/bin/osascript -e 'tell application \"System Events\" to make login item at end with properties {path:\"%@\"}'", pathOfApp];
  system(theASCommandLoginItem);
  NSLog(theASCommandLoginItem);

Here is the output:

2009-10-11 20:09:52.803 The Talking Cloud Notifier[3091:903] add to login sh: \340HH: command not found 2009-10-11 20:09:52.813 The Talking Cloud Notifier[3091:903] /usr/bin/osascript -e 'tell application "System Events" to make login item at end with properties {path:"/Users/csmith/Desktop/The Talking Cloud Notifier/build/Debug/The Talking Cloud Notifier.app"}'

At compile I also get a warning saying:

warning: passing argument 1 of 'system' from incompatible pointer type

+4  A: 

system() is a C library function and takes a regular C string (char *), not an NSString *.

You can convert the NSString into a C string by using something like [theASCommandLoginItem UTF8String]

Or you can use the Objective-C's own way of running commands, something like:

[NSTask launchedTaskWithLaunchPath:@"/usr/bin/osascript"
                         arguments:[NSArray arrayWithObjects:@"-e",
                                                             [NSString stringWithFormat:@"tell application \"System Events\" to make login item at end with properties {path:\"%@\"}", pathOfApp],
                                                             nil]];
newacct
thanks thats exactly what I wanted
Cal S
+10  A: 

Bad

As newacct's answer already suggested you have to use a C-string instead of an NSString for the system() function.

Good

Use NSTask instead.

Better

More useful for you would be the NSAppleScript class:

NSAppleScript *script;
NSDictionary *errorDict;
NSAppleEventDescriptor *returnValue;
// multi line string literal
NSString *scriptText = @"tell application 'System Events'\n"
                        "make login item at end with properties {path:\"%@\"}\n"
                        "end tell";
scriptText = [NSString stringWithFormat:scriptText, pathOfApp];
script = [[[NSAppleScript alloc] initWithSource:scriptText] autorelease];
returnValue = [script executeAndReturnError:&errorDict];
if (returnValue) {
     // success
} else {
     // failure
}

Best

Have a look at Apple's documentation on how to register your app to be a login item. There are even some examples.

Georg
thanks a lot :)
Cal S
+1 for a nice run through.
Abizern