문제

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.

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top