【问题标题】:Cocoa/Objective-c 'system();' acting weirdCocoa/Objective-c 'system();'举止怪异
【发布时间】:2009-10-11 09:21:24
【问题描述】:

我正在尝试使用 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 会说话的 Cloud Notifier[3091:903] 添加到登录 sh:\340HH:找不到命令 2009-10-11 20:09:52.813 会说话的 云通知器[3091:903] /usr/bin/osascript -e '告诉 应用程序“系统事件”制作 带有属性的登录项 {path:"/Users/csmith/Desktop/The 会说话的云通知程序/构建/调试/The Talking Cloud Notifier.app"}'

在编译时,我还收到一条警告:

警告:传递参数 1 来自不兼容指针的“系统” 输入

【问题讨论】:

    标签: objective-c cocoa terminal applescript system


    【解决方案1】:

    不好

    正如 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,了解如何将您的应用注册为登录项。甚至还有一些例子。

    【讨论】:

      【解决方案2】:

      system() 是一个 C 库函数,采用常规 C 字符串 (char *),而不是 NSString *

      您可以使用 [theASCommandLoginItem UTF8String] 之类的东西将 NSString 转换为 C 字符串

      或者您可以使用 Objective-C 自己的命令运行方式,例如:

      [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]];
      

      【讨论】:

        猜你喜欢
        • 2013-03-25
        • 2010-09-24
        • 2011-01-05
        • 2014-10-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多