Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the new JavaScriptCore framework for iOS7?

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "what is the new JavaScriptCore framework of iOS7". In the operation of actual cases, many people will encounter such a dilemma. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Classes in JavaScriptCore

After introducing JavaScriptCore into the project, in addition to the large Copyright comments in the header file, you can see that as long as five files are introduced, the class corresponding to the file name is defined in each file:

JSContext

JSValue

JSManagedValue

JSVirtualMachine

JSExport

Although the comments in the code are also described in more detail, but like the top ten thousand words in a picture, the code is more persuasive to the programmer. This article starts with JSContext and JSValue, which are relatively easy to understand but commonly used by these classes, as well as how and how their methods are used.

JSContext and JSValue

JSVirtualMachine provides the underlying resources for the operation of JavaScript, and JSContext provides a running environment for it. Through the-(JSValue *) evaluateScript: (NSString *) script; method, you can execute a JavaScript script, and if there are methods, variables and other information will be stored in it so that it can be used when needed. The creation of JSContext is based on JSVirtualMachine:-.

(id) initWithVirtualMachine: (JSVirtualMachine *) virtualMachine;, if initialized with-(id) init;, a new JSVirtualMachine object is automatically created inside it and then the previous initialization method is called.

JSValue can be said to be an interchangeable bridge between JavaScript and Object-C, providing a variety of ways to easily convert JavaScript data types to Objective-C or to the past. The one-to-one correspondence is shown in the following table:

Objective-CJavaScriptJSValue ConvertJSValue ConstructornilundefinedvalueWithUndefinedInContextNSNullnullvalueWithNullInContext:NSStringstringtoStringNSNumbernumber, booleantoNumber

ToBool

ToDouble

ToInt32

ToUInt32valueWithBool:inContext:

ValueWithDouble:inContext:

ValueWithInt32:inContext:

ValueWithUInt32:inContext:NSDictionaryObject objecttoDictionaryvalueWithNewObjectInContext:NSArrayArray objecttoArrayvalueWithNewArrayInContext:NSDateDate objecttoDateNSBlockFunction objectidWrapper objecttoObject

ToObjectOfClass:valueWithObject:inContext:ClassConstructor object basic type conversion

Let's start with a simple example:

1 JSContext * context = [[JSContext alloc] init]; 2 JSValue * jsVal = [context evaluateScript:@ "21th 7"]; 3 int iVal = [jsVal toInt32]; 4 NSLog (@ "JSValue:% @, int:% d", jsVal, iVal); 5 6 / / Output:7 / / JSValue: 28, int: 28

Very simple, you can also save a JavaScript variable in JSContext, and then through the subscript to get it. For Array or Object types, JSValue can also be directly evaluated and assigned by subscript.

1 JSContext * context = [[JSContext alloc] init]; 2 [context evaluateScript:@ "var arr = [21, 7, 'iderzheng.com'];"]; 3 JSValue * jsArr = context [@ "arr"]; / / Get array from JSContext 4 5 NSLog (@ "JS Array:% @; Length:% @", jsArr, jsArr [@ "length"]); 6 jsArr [1] = @ "blog"; / / Use JSValue as array 7 jsArr [7] = @ 7 8 9 NSLog (@ "JS Array:% @; Length:% d", jsArr, [jsArr [@ "length"] toInt32]); 10 11 NSArray * nsArr = [jsArr toArray]; 12 NSLog (@ "NSArray:% @", nsArr) 13 14 / / Output:15 / / JS Array: 21 Length: 316 / / JS Array: 21 JS Array 7 Length: 817 / / NSArray: (18 / 21 / 19 / blog,20 / / "iderzheng.com", 21 / ", 22 /", 23 / ", 24 /", 25 / 726 / /)

From the output, it is easy to see that the code successfully assigns data from Objective-C to the JavaScript array, and JSValue follows the array characteristics of JavaScript: no subscript offside, automatic extension of the array size. And you can also get the properties on the JavaScript object through JSValue, such as the length of the JavaScript array through "length" in the example. When converted to NSArray, all the information is also correctly converted to the past.

Transformation of method

Various data types can be converted, and the Block of Objective-C can also be passed into JSContext as a method of JavaScript. For example, although JavaScritpCore does not come with the log method commonly used in front-end development (after all, it does not run on a web page, there will be no classes such as window, document, and console), you can still define a Block method to call NSLog to simulate:

1 JSContext * context = [[JSContext alloc] init]; 2 context [@ "log"] = ^ () {3 NSLog (@ "+ Begin Log+"); 4 5 NSArray * args = [JSContext currentArguments]; 6 for (JSValue * jsVal in args) {7 NSLog (@ "% @", jsVal); 8} 9 10 JSValue * this = [JSContext currentThis]; 11 NSLog (@ "this:% @", this) 12 NSLog (@ "- End Log-"); 13}; 14 15 [context evaluateScript:@ "log ('ider', [7,21], {hello:'world', js:100});"] 16 17 / / Output:18 / + Begin Log+19 / / ider20 / / 7 object Object 2121 / / [object Object] 22 / / this: [object GlobalObject] 23 / /-End Log-

Successfully call the method in JavaScript through Block to return to Objective-C, and still follow the various characteristics of the JavaScript method, such as the method parameters are not fixed. Because of this, JSContext provides class methods to get the parameter list (+ (JSContext *) currentContext;) and the object currently calling the method (+)

(JSValue *) currentThis). For "this", the output is GlobalObject, which is also the JSContext object method-(JSValue

*) the content returned by globalObject;. Because we know that in JavaScript, all global variables and methods are actually properties of a global variable, which is window in the browser, but what it is in JavaScriptCore is unknown.

Block can be passed in JSContext as a method, but JSValue does not have a toBlock method to turn the JavaScript method into Block for use in Objetive-C. After all, the number of parameters and the type returned by Block are fixed. Although the method cannot be extracted, JSValue provides-

(JSValue *) callWithArguments: (NSArray *) the arguments; method can, in turn, pass parameters in to invoke the method.

1 JSContext * context = [[JSContext alloc] init]; 2 [context evaluateScript:@ "function add (a, b) {return a + b;}"]; 3 JSValue * add = context [@ "add"]; 4 NSLog (@ "Func:% @", add); 5 6 JSValue * sum = [add callWithArguments:@ [@ (7), @ (21)]]; 7 NSLog (@ "Sum:% d", [sum toInt32]) 8 / / OutPut: 9 / / Func: function add (a, b) {return a + b;} 10 / / Sum: 28

JSValue also provides-(JSValue *) invokeMethod: (NSString *) method withArguments: (NSArray *) arguments; so that we can simply call methods on the object directly. It's just that if the defined method is a global function, it's obvious that the method should be called on the globalObject object of JSContext; if it's a method on a JavaScript object, it should be called with the corresponding JSValue object.

Exception handling

Exceptions to Objective-C are caught by Xcode at run time, while JavaScript executed in JSContext, if an exception occurs, is only caught by JSContext and stored on the exception property, not thrown out. It is obviously not appropriate to check whether the exception of the JSContext object is not nil all the time. It is more reasonable to set exceptionHandler to the JSContext object, which accepts ^ (JSContext).

Block in the form of * context, JSValue * exceptionValue). Its default value is to assign the incoming exceptionValue to the exception property of the incoming context:

1 ^ (JSContext * context, JSValue * exceptionValue) {2 context.exception = exceptionValue;3}

We can also give exceptionHandler a new Block so that when an exception occurs in the JavaScript operation, we can immediately know:

1 JSContext * context = [[JSContext alloc] init]; 2 context.exceptionHandler = ^ (JSContext * con, JSValue * exception) {3 NSLog (@ "% @", exception); 4 con.exception = exception; 5}; 6 7 [context evaluateScript:@ "ider.zheng = 21"]; 8 9 / / Output:10 / / ReferenceError: Can't find variable: precautions for ider using Block

From the previous examples and introductions, we should realize the powerful role of Block in JavaScriptCore. It builds more bridges between JavaScript and Objective-C and makes intercommunication more convenient. However, it should be noted that whether passing Block to a JSContext object to become a JavaScript method, or assigning it to the exceptionHandler property, do not directly use its externally defined JSContext object or JSValue within the Block, but should pass it as a parameter to the Block, or through the JSContext class method +

(JSContext *) currentContext; to get. Otherwise, it will cause circular references so that memory cannot be freed correctly.

For example, the above custom exception handling method is assigned to the incoming JSContext object con instead of the context object created outside it, even though they are actually the same object. This is because Block makes strong references to objects created by external definitions that are used internally, and JSContext also makes strong references to the given Block, so that circular references (Circular) are formed between them.

Reference) prevents memory from being freed properly.

JSValue cannot be referenced directly into Block from outside, because there is a reference to JSContext (@ property (readonly, retain) JSContext) on every JSValue.

* context;), JSContext and then reference Block will also form a reference loop.

This is the end of the content of "what is the New JavaScriptCore Framework for iOS7". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report