6

我正在尝试向我编写的 Cocoa 应用程序添加一些脚本功能。我为我的项目创建了一个sdef(脚本定义文件)。到目前为止,我已经成功地使用 AppleScript 访问对象子项(元素),但我一生都无法弄清楚如何调用方法(命令)。

这是我的 sdef 文件。

<suite name="mySuite" code="mSUI" description="My Application Suite">
    <class name="application" code="capp" description="Top level scripting object.">
        <cocoa class="NSApplication"/>
        <!-- I can access these elements fine -->
        <element description="Test children." type="child" access="r">
            <cocoa key="myChildren"/>
        </element>
        <!-- Cannot seem to call this method :( -->
        <responds-to command="testmethod">
            <cocoa method="exposedMethod:"/>
        </responds-to>
    </class>
    <class name="child" code="cHIL" description="A Child." plural="children">
        <cocoa class="Child"/>
        <property name="name" code="pnam" description="The child name." type="text" access="r">
            <cocoa key="name"/>
        </property>
    </class>
    <command name="testmethod" code="tEST" description="Execute the test method" />
</suite>

这是我的控制器类实现(这是我的应用程序的委托)

我的控制器.h

#import <Cocoa/Cocoa.h>

@interface MyController : NSObject {
    NSMutableArray* myChildren;
}
// Some Methods

@end

MyController+Scripting.m

#import "MyController+Scripting.h"

@implementation MyController (Scripting)

// This works when I'm accessing the myChildren 
- (BOOL)application:(NSApplication*)sender delegateHandlesKey:(NSString*)key { 
    NSLog(@"Key = %@", key);
  return ([key isEqualToString:@"myChildren"]);
}
// This does NOT work...
- (void)exposedMethod:(NSScriptCommand*)command {
    NSLog(@"Invoked Test Script Method %@", [command description]);
}

@end

最后,我正在尝试的 AppleScript 是:

tell application "MyApplication"
    testmethod
end tell

回应"AppleScript Error - The variable testmethod is not defined."

有什么想法我在这里做错了吗?我觉得我错过了一些简单的东西,但我的谷歌搜索似乎没有找到任何有用的东西。

4

3 回答 3

2

事情看起来基本正确,但代码<command/>应该是两部分代码(八个字符)而不是四个。

于 2009-07-30T16:43:14.120 回答
2

我刚刚在此处发布了有关如何添加带有参数的命令的详细解决方案:https ://stackoverflow.com/a/10773994/388412

简而言之:我认为您应该继承 NSScriptCommand并覆盖-(void)performDefaultImplementation而不是在控制器中公开方法。至少那是我从文档中提炼出来的:

“此命令是 NSScriptCommand 的子类,包含一个方法 performDefaultImplementation。该方法覆盖 NSScriptCommand 中的版本”

……对我来说效果很好,有关详细信息,请参阅我的链接答案。

于 2012-05-27T12:41:08.227 回答
1

(实际上,我从未向 Cocoa 应用程序添加脚本功能,所以请在黑暗中用一粒盐来刺伤我。)

我猜的第一件事是它exposedMethod:需要一个参数,但我看不到在你的 sdef 或 AppleScript 中可能指定的位置。事实上,AppleScript 看起来像是testmethod一个变量,而不是一个命令。(也许它应该是类似“ testmethod with ...”的东西?)您可能需要在 sdef 中为命令定义一个<parameter>or元素。<direct-parameter>

另外,您不需要一个对象来调用该方法吗?由于您的控制器是应用程序委托,我不确定那里的复杂性,但 AppleScript 是否会尝试testMethod:在 NSApplication 而不是您的委托上调用?

我猜您已经查看了 Apple 的示例代码和其他资源,但如果没有,这里有一些链接可能会有所帮助:

祝你好运!

于 2009-07-29T17:07:05.197 回答