0

I have a problem changing an object passed into JavaScriptCore.

Here is my custom object, defining a single String property called testProperty:

import Foundation
import JavaScriptCore

protocol JSCustomObjectExport: JSExport {
    var testProperty: String { get set }
}

class JSCustomObject: NSObject, JSCustomObjectExport {
    var testProperty: String = "ABC"
}

Here is the AppDelegate in which I create a JSContext, pass my custom object to it and run a JS script to change its testProperty from "ABC" to "XYZ". However the testProperty is never changed.

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"
    }

}

Am I doing something wrong? Shouldn't co.testProperty change?

Btw, this is an OS X app, compiled in XCode 6.1.1 on OSX 10.10.1.

1 Answer 1

2

It seems, it requires that the protocol is marked as @objc, and the class has explicit @objc export name.

I tried the following script in Playground, and it works

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
Sign up to request clarification or add additional context in comments.

2 Comments

Help. This doesn't work properly any more in the latest xcode 7.2 playground :( This prints "ABC" instead of "XYZ"
It seems as playground bug. The sample works good also in playground only if class and protocol are marked as public and moved to separate file in playground Sources folder.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.