1

I'm using JavascriptCore in my app. Now, I'm passing some variables to the JSContext that can then be passed back to Objective-C. However, one of the variables, an NSDictionary, is not passing through correctly. I run the code below:

var evaluate = function(variables) {
    app.setDictionary(variables.dictionary);
}

This is a simple example that has these following methods set up in JSContext.

This is the setDictionary() method:

- (void)setDicationary:(NSDictionary *)dictionary {
    self.mutableDictionary = [dictionary mutableCopy];
}

This is variables.dictionary:

- (NSDictionary *)dictionary {
    return self.values;
}

And this is how I call evaluate():

JSValue *jsFunction = self.context[@"evaluate"];
JSValue *value = [jsFunction callWithArguments:@[self.variables]];

However, in the setDictionary method, I don't get an NSDictionary, but instead get a NSString containing [object Object].

Any ideas how I can solve this?

2
  • Please, add Objective-C code counterpart to the question. Commented Mar 28, 2017 at 10:52
  • @BorisVerebsky I added it! Commented Mar 28, 2017 at 10:58

1 Answer 1

1

Although JavaScriptCore automatically converts types between Objective-C or Swift and JavaScript, I suggest to implement explicit conversion. Automatic conversion doesn't always work as developer may expect. For example undefined is converted to @"undefined" in case, when NSString is used.

Try something like:

- (void)setDicationary:(JSValue *)jsDictionary {
    if ([jsDictionary isUndefined] || [jsDictionary isNull]) {
        jsDictionary = nil;
    }
    self.mutableDictionary = [jsDictionary toDictionary];
}

Note that JavaScript uses object as dictionary, so you should be very careful with argument that you passing to Objective-C code. Passing any system object will result to recursive conversion of that object to NSDictionary.

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.