我正在尝试使用 system() 在我的 Cocoa 应用程序中运行 applescript;函数 - 我传递给函数的字符串在终端中工作,并且 applescript 本身很好,我认为它与 NSString 有关 - 有人可以帮忙吗?
//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);
这是输出:
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"}'
在编译时我还收到一条警告:
warning: passing argument 1 of 'system' from incompatible pointer type
最佳答案
不好
正如 newacct 的答案已经建议的那样,对于 system()
函数,您必须使用 C 字符串而不是 NSString
。
好
改用NSTask
。
更好
对您来说更有用的是 NSAppleScript
类:
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
}
最好
看看Apple's documentation关于如何将您的应用程序注册为登录项。甚至还有一些例子。
关于objective-c - Cocoa/Objective-c 'system();' 表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1550254/