Search code examples
swiftjavascriptcore

Create JSStringRef in Swift


I'm using the new (i.e., Objective-C) JavaScriptCore API in Swift. However, JSContext's evaluateScript method doesn't support the source URL and starting line number parameters that JSEvaluateScript (from the C API) does, so I'm trying to call the C method from my Swift code.

The C method takes JSStringRefs instead of Strings, so I need to create those. When I try the obvious solution:

println(JSStringCreateWithCFString("an example").takeRetainedValue())

I get an EXC_BAD_ACCESS (code=EXC_I386_GPFLT). (I'm using takeRetainedValue() because the documentation notes that JSStringCreateWithCFString follows the Create Rule, but takeUnretainedValue() gives me the same error). What am I doing wrong?


Solution

  • This was a bug in the Swift header for JavaScriptCore. The correct code would now be, for example:

    import JavaScriptCore
    
    let str = JSStringCreateWithCFString("an example")
    let len = JSStringGetLength(str)
    JSStringRelease(str)