JavaScriptCore and Swift "this class is not key value coding-compliant for the key test"

616 views Asked by At

I can't for the life of me pass a dictionary (in this case containing a SKLabelNode) or any other object to JavaScriptCore in Swift. I've taken this short sample straight out of a "command line tool" template project I just created in Xcode.

import Foundation
import JavaScriptCore
import SpriteKit

let context = JSContext()
let label = SKLabelNode(text:"Test")
context.setValuesForKeysWithDictionary(["test": label])

This throws me an exception:

2014-11-16 18:07:47.104 JSCoreTest[10139:193484] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<JSContext 0x1008268d0> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key test.'

I am using Xcode 6.1 on Yosemite. Can anyone reproduce my issue and solve it?

UPDATE:

I thought that perhaps it didn't work because I didn't "JSExport" the object, so I tried with this example, but I still get the same error:

protocol MyObjExport: JSExport {
    var foo: String! { get }
}

class MyObj: NSObject, MyObjExport {
    var foo: String! { return "bar" }
}


let context = JSContext(virtualMachine: JSVirtualMachine())
context.setValuesForKeysWithDictionary(["test": MyObj()])
1

There are 1 answers

1
dbotha On BEST ANSWER

You're using the wrong method. You want to use setObject:forKeyedSubscript: from JSContext and not setValuesForKeysWithDictionary: from the NSKeyValueCoding protocol (which JSContext does not conform to) i.e. :

let context = JSContext()
let label = SKLabelNode(text:"Test")
context.setObject(label, forKeyedSubscript: "test")