objective-c - Cocoa/Objective-c 'system();' 表现得很奇怪

标签 objective-c cocoa terminal applescript system

我正在尝试使用 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/

相关文章:

ios - 实现级联删除的Realm最佳实践

cocoa - 用于 NSURL 书签的 Finder 风格 UI 丢失文件的数据解析?

node.js - 如何隐藏mongo终端的输出(Node.Js)

mysql - 如何在 Ubuntu 中更新 phpMyAdmin?

objective-c - 未使用的属性访问结果

iphone - 即使应用程序未运行,如何调用方法? iOS

objective-c - 在快速枚举中输入正确的值

cocoa - 更改 fsevents 中的 pathsToWatch

linux - 如何将多行 bash 代码粘贴到终端并一次运行?

ios - 类名的 NSString 占位符