shr*_*sva 34 cocoa applescript objective-c
我是Cocoa编程世界的新手,我想在我的应用程序中添加Applescript支持.Apple网站上的例子似乎已经过时了.
如何向我的Cocoa应用程序添加Applescript支持?
auc*_*uco 44
如果要从应用程序发送AppleScript并需要沙盒应用程序,则需要创建临时授权
您需要在info.plist中添加这两个键
<key>NSAppleScriptEnabled</key>
<true/>
<key>OSAScriptingDefinition</key>
<string>MyAppName.sdef</string>
Run Code Online (Sandbox Code Playgroud)...当然,您必须将"MyAppName"更改为您应用的名称
创建.sdef文件并将其添加到项目中.更进一步的课程现在很大程度上取决于您的应用程序的需求,有:
-
转到此处查找详细说明及其实施的许多详细信息:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/ScriptableCocoaApplications/SApps_script_cmds/SAppsScriptCmds.html
我发现使用Class和KVC Elements非常复杂,因为我只想执行一个命令,没什么特别的.因此,为了帮助其他人,这里是一个如何使用一个参数创建一个新的简单命令的示例.在这个例子中,它将"查找"一个这样的字符串:
tell application "MyAppName"
lookup "some string"
end tell
Run Code Online (Sandbox Code Playgroud)此命令的.sdef文件如下所示:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE dictionary SYSTEM "file://localhost/System/Library/DTDs/sdef.dtd">
<dictionary title="MyAppName">
<suite name="MyAppName Suite" code="MApN" description="MyAppName Scripts">
<command name="lookup" code="lkpstrng" description="Look up a string, searches for an entry">
<cocoa class="MyLookupCommand"/>
<direct-parameter description="The string to lookup">
<type type="text"/>
</direct-parameter>
</command>
</suite>
</dictionary>
Run Code Online (Sandbox Code Playgroud)创建NSScriptCommand的子类并将其命名为MyLookupCommand
MyLookupCommand.h
#import <Foundation/Foundation.h>
@interface MyLookupCommand : NSScriptCommand
@end
Run Code Online (Sandbox Code Playgroud)
MyLookupCommand.m
#import "MyLookupCommand.h"
@implementation MyLookupCommand
-(id)performDefaultImplementation {
// get the arguments
NSDictionary *args = [self evaluatedArguments];
NSString *stringToSearch = @"";
if(args.count) {
stringToSearch = [args valueForKey:@""]; // get the direct argument
} else {
// raise error
[self setScriptErrorNumber:-50];
[self setScriptErrorString:@"Parameter Error: A Parameter is expected for the verb 'lookup' (You have to specify _what_ you want to lookup!)."];
}
// Implement your code logic (in this example, I'm just posting an internal notification)
[[NSNotificationCenter defaultCenter] postNotificationName:@"AppShouldLookupStringNotification" object:stringToSearch];
return nil;
}
@end
Run Code Online (Sandbox Code Playgroud)
基本上就是这样.这样做的秘诀是子类化NSScriptCommand并覆盖performDefaultImplementation.我希望这可以帮助别人更快地完成它...
小智 4
现代版本的 Cocoa 可以直接解释脚本定义 (.sdef) 属性列表,因此对于基本 AppleScript 支持,您所需要做的就是根据文档创建 sdef,将其添加到“复制捆绑资源”阶段并声明 AppleScript 支持在你的 Info.plist 中。要访问 NSApp 以外的对象,您需要定义对象说明符,以便每个对象都知道其在脚本世界层次结构中的位置。这使您能够对对象属性进行 kvc 操作,并能够将对象方法用作简单的脚本命令。
归档时间: |
|
查看次数: |
7653 次 |
最近记录: |