我在更改传递到 JavaScriptCore 的对象时遇到问题。
这是我的自定义对象,定义了一个名为 testProperty 的字符串属性:
import Foundation
import JavaScriptCore
protocol JSCustomObjectExport: JSExport {
var testProperty: String { get set }
}
class JSCustomObject: NSObject, JSCustomObjectExport {
var testProperty: String = "ABC"
}
这是 AppDelegate,我在其中创建 JSContext,将自定义对象传递给它并运行 JS 脚本以将其 testProperty 从“ABC”更改为“XYZ”。然而 testProperty 永远不会改变。
import Cocoa
import JavaScriptCore
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet var window: NSWindow!
lazy var context = JSContext()
func applicationDidFinishLaunching(aNotification: NSNotification?) {
println("Started")
var co = JSCustomObject()
context.globalObject.setValue(co, forProperty: "customObject")
context.evaluateScript("customObject.testProperty = 'XYZ'")
println(co.testProperty) // ERROR(?): This prints "ABC" instead of "XYZ"
}
}
我做错了什么吗? co.testProperty 不应该改变吗?
顺便说一句,这是一个 OS X 应用程序,在 OSX 10.10.1 上的 XCode 6.1.1 中编译。
最佳答案
看来,它要求协议(protocol)被标记为@objc
,并且类有明确的@objc
导出名称。
我在 Playground 中尝试了以下脚本,它有效
import Foundation
import JavaScriptCore
@objc // <- HERE
protocol JSCustomObjectExport: JSExport {
var testProperty: String { get set }
}
@objc(JSCustomObject) // <- HERE
class JSCustomObject: NSObject, JSCustomObjectExport {
var testProperty: String = "ABC"
}
var context = JSContext()
var co = JSCustomObject()
context.globalObject.setValue(co, forProperty: "customObject")
context.evaluateScript("customObject.testProperty = 'XYZ'")
println(co.testProperty) // -> XYZ
关于macos - 使用 JavaScriptCore 更改 JSContext 传递的 Swift 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27034803/