您的位置:首页 > 移动开发 > Objective-C

objectc 与 js 交互

2015-06-09 16:27 453 查看
Execute Javascript in iOS Applications

In this tutorial, I have covered How to execute JavaScript in iOS / Objective-C. You can execute JavaScript in iOS applications with the help of JavaScriptCore.framework. This framework is supported in iOS7 & OSX 10.9

List of features supported by Javascript.framework

a) Evaluate JavaScript code in Objective-C

b) Access JavaScript Variables in Objective-C

c) Access JavaScript functions and execute them in Objective-C

d) Execute Objective-C code from JavaScript

e) Export Objective-C classes and use them in JavaScript.

Download the source code:



To access JavaScript framework, you need to include the header file

List of Main Classes supported by framework:

JSContext : For any javascript operations you need JSContext.

JSValue : JSValue holds JavaScript values,variables and functions. List of main methods in JSValue.



Accessing Javascript Code in Objective-C

1).Evaluating Javascript Code

2).Access Javascript Variables. Variables and functions are accessed from JSContext.

To access varible from Javascript : context[@"x"]

To access function from javascript : context[@"myfun"]

3).Access Javascript functions and execute them in Objective-C



Call Objective-C code from JavaScript

Objective-C code is called from JavaScript in two ways


1.CODE BLOCKS

Objective-C code block can be called from JavaScript.


2.USING JSEXPORT PROTOCOL

You can see the comparison between Objective-C Object and it’s equivalent Javascript Object below.
To make Javascript interacting with Objective-C Object, We need to have a Protocol which should be inherited

from JSExport. Move all the variables and functions to prototype to access them in JavaScript.

Now MyObject(Objective-C)’s variables and functions are directly accessed from javascript.

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: