2

I'm using JavaScriptCore to evaluate some simple scripts in my app. I'm creating a global object and defining some properties on it like so:

JSContext *context = [[JSContext alloc] init];
JSValue *globalObject = [context globalObject];

[globalObject setValue:fields forProperty:@"fields"];
...

So then the script can access the values in fields and so on. I'd like scripts to be able to use a function called lookup, and I already have an Objective-C implementation for this function.

How do I add a property to the global object which is a function that calls back to my Objective-C method? I see that there's a function called JSObjectMakeFunctionWithCallback, but that uses the low-level C constructs like JSObjectRefs and takes a C function, not an Objective-C block, so I can't make use of self inside the implementation.

1 Answer 1

1

You can pass an Objective-C block to a JSContext and it will then behave as a function. That way, your scripts can call back into your iOS code:

context[@"factorial"] = ^(int x) {
    int factorial = 1;
    for (; x > 1; x--) {
        factorial *= x;
    }
    return factorial;
};
[context evaluateScript:@"var fiveFactorial = factorial(5);"];
JSValue *fiveFactorial = context[@"fiveFactorial"];
NSLog(@"5! = %@", fiveFactorial);

Source: Bignerdranch

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.