【问题标题】:Adding a variable to applescript within obj-c在 obj-c 中向 applescript 添加变量
【发布时间】:2016-03-12 07:21:46
【问题描述】:

不确定在没有将脚本作为文件并以这种方式运行的情况下,这是否可以在 Objective-c 中实现。

    NSAppleScript *appleScriptGetHH = [[NSAppleScript alloc] initWithSource:@\
                              "tell application \"System Events\"\n \
                              tell process \"Grabee\"\n \
                              with timeout of 0 seconds\n \
                              get value of attribute \"AXValue\" of text area 1 of scroll area 1 of window \"Demo Window 1" \n \
                              end timeout \n \
                              end tell \n \
                              end tell"];

这很好用,但我想做的是用字符串替换“Demo Window 1”(因为它将在程序中动态更改)

当我使用这样的东西时

NSString *windowName = @"Green Window4";

然后替换这一行:

get value of attribute \"AXValue\" of text area 1 of scroll area 1 of window \"Demo Window 1" \n \

与:

get value of attribute \"AXValue\" of text area 1 of scroll area 1 of window \"%@" \n \

还有

end tell", windowName];

我收到一个参数太多的错误,有没有办法在不分离脚本的情况下做到这一点?

【问题讨论】:

    标签: objective-c applescript


    【解决方案1】:

    像这样构建字符串;

      NSAppleScript *appleScriptGetHH = [[NSAppleScript alloc] initWithSource:
             [[NSString alloc] initWithFormat:@\
                              "tell application \"System Events\"\n \
                              tell process \"Grabee\"\n \
                              with timeout of 0 seconds\n \
                              get value of attribute \"AXValue\" of text area 1 of scroll area 1 of window \"%@"  \n \
                              end timeout \n \
                              end tell \n \
                              end tell", windowName]
      ];
    

    或将字符串构建为单独的步骤以提高可读性。

    【讨论】:

    • 我得到“'Nsapplescript' 没有可见的@interface 声明选择器'initwith.......' 嗯
    • 我在 [NSString 之前遗漏了一个 [
    • 哦,我多么希望每个未通过“代码注入 101”的布偶都能得到一美元。 永远不要评估包含未经处理的输入的生成代码。 这是一场安全灾难和可靠性噩梦。 Here's the correct, safe way 参数化通过 NSAppleScript 运行的 AppleScript。或者,如果 AppleScript 代码是您的应用程序的一部分(而不是用户提供的),只需使用 AppleScriptObjC bridge 直接调用您的 AS 处理程序。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    • 2016-10-17
    • 2011-06-07
    相关资源
    最近更新 更多