首页 > 解决方案 > 如何从可编写脚本的程序中将数组返回到 AppleScript?

问题描述

我正在尝试使我的应用程序可编写脚本,而我想做的一件事是从我的应用程序返回一个数组并进入 AppleScript,以便可以在那里进一步处理它。我想我可以通过返回数组的计数来做到这一点,然后让 AppleScript 从 1 迭代到 n 以返回数组中的每个项目 - 但我认为这不会非常有效。

我的代码目前如下所示:

sdef 文件的相关部分

        <command name="List" code="lflecont" description="List file types found in data stream">
            <cocoa class="ListDataContentCommand"/>
            <result description="an array containing the types of all the data blocks in the File">
                <type type="any" list="yes"/>
            </result>
        </command>

ListDataContentCommand.h

@interface ListDataContentCommand : NSScriptCommand

@end

列表数据内容命令.m

@implementation ListDataContentCommand

-(id)performDefaultImplementation {
    return @[@"Jam",@"Fish",@"Eggs"];
}

@end

为了测试这一点,我创建了以下简单的 AppleScript……</p>

tell application "Data Dump"
    open "/Volumes/Test Data/test.dat"
    set theList to List
end tell

这会返回一个错误 -error "Data Dump got an error: Can’t continue List." number -1708

如何让我的数组输出?

就此而言,如何返回 NSDictionary?或者那是不可能的?NSString 可以直接返回到文本 - 还是需要先转换为 Cstring?

新手问题,恐怕,但关于 AppleScript 的好信息似乎很难获得!

标签: objective-ccocoaapplescript

解决方案


一般来说,如果你想通过 AppleScript 返回一个项目列表,你可以如下设置 sdef 的命令 XML,将result元素扩展为一个块,并包含一个属性设置为 'yes'的type元素:list

<command name="List" code="lflecont" description="List file types found in data stream">
    <cocoa class="ListDataContentCommand"/>
    <result description="an array containing the types of all the data blocks in the File">
        <type type="any" list="yes"/>
    </result>
</command>

然后在你的performDefaultImplementation方法结束时,你需要做的就是返回一个标准的 cocoa NSArray。Cocoa 脚本自动将数组转换为 AppleScript 列表,将所有子元素转换为适当的形式。

-(id)performDefaultImplementation {
    NSArray * resultArray

    // do whatever that adds values to resultArray
    return resultArray;
}

我担心的一个问题是您似乎正在使用通知做某事,如果输出取决于异步操作(如通知回复),您可能需要开始考虑暂停和恢复苹果事件。请记住,AppleScript 不是线程化的,因此如果应用程序正在处理一个事件(等待异步操作)并接收到第二个事件,则结果是不确定的(并且可能令人不快)。


推荐阅读