Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[JavaScriptCore] Objective-C调用JavaScript #20

Open
jschyz opened this issue Sep 4, 2018 · 0 comments
Open

[JavaScriptCore] Objective-C调用JavaScript #20

jschyz opened this issue Sep 4, 2018 · 0 comments

Comments

@jschyz
Copy link
Owner

jschyz commented Sep 4, 2018

例如有一个"hello.js"文件内容如下:

function printHello() {
 
}

在Objective-C中调用printHello方法:

NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"hello" ofType:@"js"];
NSString *scriptString = [NSString stringWithContentsOfFile:scriptPath encoding:NSUTF8StringEncoding error:nil];
 
JSContext *context = [[JSContext alloc] init];
[context evaluateScript:scriptString];
 
JSValue *function = context[@"printHello"];
[function callWithArguments:@[]];

分析以上代码:

首先初始化了一个JSContext,并执行JavaScript脚本,此时printHello函数并没有被调用,只是被读取到了这个context中。

然后从context中取出对printHello函数的引用,并保存到一个JSValue中。

注意这里,从JSContext中取出一个JavaScript实体(值、函数、对象),和将一个实体保存到JSContext中,语法均与NSDictionary的取值存值类似,非常简单。

最后如果JSValue是一个JavaScript函数,可以用callWithArguments来调用,参数是一个数组,如果没有参数则传入空数组@[]。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant