objective-c - 在我的可编写脚本的应用程序中为 "make new"提供我自己的对象

标签 objective-c macos applescript scriptable

这是一个关于使用 Cocoa Scripting 实现可编写脚本的应用程序的问题。

我的应用程序可编写脚本 application对象包含自定义类的元素,我们称之为 flower .

在 .sdef 文件中,flower 的 Cocoa 类指定为ScriptableFlower .

在 Applescript 中,现在可以编写:

tell app "myapp"
  get flowers
end tell

我的代码提供了用于检索花的访问器函数:-(NSArray*)flowers .

现在,我想实现一种添加新花的方法,以便可以编写:

tell app "myapp"
  make new flower
end tell

此行为的默认行为,“make”的默认核心套件处理程序使用 NSCreateCommand ,如下:

脚本引擎将通过调用我的flowers来获取当前的花数组。函数,然后实例化类 ScriptableFlower 的新 Cocoa 对象,然后调用setFlowers:(NSArray*)一个数组包含我的原始对象和新创建的对象。

但是,这对我的应用程序不利:我不能允许脚本引擎随意创建可编写脚本的类的对象。

相反,我需要成为实例化它们的人。

一个折衷的解决方案是实现默认的 -(id)init方法,然后检测它是否是我调用的 - 如果不是,我可以采取额外的步骤。但这并不干净。我宁愿根本不让脚本引擎创建新对象,而是自己提供它们,因为我可能已经在“某处”准备好了对象。

Cocoa Scripting 中是否有一些规定会导致它在需要我创建新的可编写脚本的对象时调用我?

更新

澄清一下:Cocoa Scripting docs解释说,我们可以实现特殊的插入处理程序(insertObject:in<Key>AtIndex:),这样就不必获取整个 NSArray,但这仍然会导致脚本引擎创建对象。不过,我需要被要求创建该对象。

最佳答案

文件NSObjectScripting.h为此提供了一个函数:

- (id)newScriptingObjectOfClass:(Class)objectClass forValueForKey:(NSString *)key withContentsValue:(id)contentsValue properties:(NSDictionary *)properties;

它自 OS X 10.5 起可用,记录如下:

Create a new instance of a scriptable class to be inserted into the relationship identified by the key, set the contentsValue and properties of it, and return it. Or return nil for failure. The contentsValue and properties are derived from the "with contents" and "with properties" parameters of a Make command. The contentsValue may be nil. When this method is invoked by Cocoa neither the contentsValue nor the properties will have yet been coerced using scripting key-value coding's -coerceValue:forKey: method. In .sdef-declared scriptability the types of the passed-in objects reliably match the relevant .sdef declarations however.

关于objective-c - 在我的可编写脚本的应用程序中为 "make new"提供我自己的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36239533/

相关文章:

ios - 以编程方式符号化地址

macos - Applescript 将启动 Chrome(具体内容)

iphone - 如何释放手动保留的类对象

ios - 获取 UIButton 的标签和标签较小的标签

ios - 使用 iOS Photos Framework 如何列出所有可用的 PHAssetCollections?

vim - Mac OS X 中看到的 CLI Vim 进程的名称是什么?

timestamp - AppleScript:QuickTime 影片录制完成后自动保存

c# - 将 .NET DateTime.Ticks 属性转换为 Objective-C 中的日期

macos - 需要使用 pkgbuild 在组件包中重新启动

objective-c - Cocoa API 的 C 绑定(bind)?