Reputation: 25983
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 JSObjectRef
s and takes a C function, not an Objective-C block, so I can't make use of self
inside the implementation.
Upvotes: 2
Views: 512
Reputation: 8501
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
Upvotes: 1