2

I'm trying to use a Swift class with JavaScriptCore. This is what I have:

import JavaScriptCore

@objc(MyObjExport) // explicit name required for class_copyProtocolList to work
public protocol MyObjExport: JSExport {
    var foo: String! { get }
}

@objc(MyObj)
public class MyObj: NSObject, MyObjExport
{
    public var foo: String! { return "bar" }
}

Which produces the following "MyModule-Swift.h" header:

SWIFT_PROTOCOL("MyObjExport")
@protocol MyObjExport <JSExport>
@property (nonatomic, readonly, copy) NSString * foo;
@end

SWIFT_CLASS("MyObj")
@interface MyObj : NSObject <MyObjExport>
@property (nonatomic, readonly, copy) NSString * foo;
@end

I can create and use this object just fine from other Obj-C code, but:

MyObj *foo = [[MyObj alloc] init];

[JSValue valueWithObject:foo inContext:nil]; // EXC_BAD_ACCESS

It crashes in the JSCore implementation:

#0  0x00007fff87c5ca73 in objectToValueWithoutCopy(JSContext*, objc_object*) ()
#1  0x00007fff87c5c27e in objectToValue(JSContext*, objc_object*) ()
#2  0x00007fff87c5c20c in +[JSValue valueWithObject:inContext:] ()

(Nothing is logged to the console.) If I implement the class in Obj-C instead of Swift, it works fine. What's wrong and how can I fix this?

1 Answer 1

1

Surely you don't want the JSContext that you're passing creating the JSValue with to be nil?

I tried with a non-nil context and I can successfully instantiate a JSValue, with a nil context it crashes with EXC_BAD_ACCESS.

This would work:

JSContext *context = [[JSContext alloc] init];
MyObj *foo = [[MyObj alloc] init];
[JSValue valueWithObject:foo inContext:context];
Sign up to request clarification or add additional context in comments.

Comments

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.