This framework is only based on the WebKit in a C + + implementation of the JavaScriptCore of a wrapper, in the previous version of iOS development, many developers will own WebKit library into the project compiled use. But although iOS7 it as a standard library, unfortunately, I haven't found an official document in Apple developer that describes how this framework is used, as it did in previous articles.
Fortunately, you can also find the header file in Xcode, and the comments inside the function of each class and method to write a clear, and then combined with the online only a few articles on the introduction, I also here a simple introduction to JavaScriptCore. More details are being discovered during the development process.
Classes in the JavaScriptCore
Javascriptcore_head
After the introduction of JavaScriptCore in the project, the chain header file, in addition to the large paragraph of the copyright note can be seen as long as the introduction of 5 files, each file is defined with the name of the corresponding class:
Jscontext
Jsvalue
Jsmanagedvalue
Jsvirtualmachine
Jsexport
Although the comments in the code are more detailed, the code is more convincing to the programmer, as is the case at the top of the graph. In this paper, we first say that these classes are relatively good to understand but also very common jscontext and jsvalue and their methods of use and effect.
Jscontext and Jsvalue
Jsvirtualmachine provides the underlying resources for the operation of JavaScript, and Jscontext provides it with a running environment through-(Jsvalue ) Evaluatescript: (nsstring ) script , the method can execute a JavaScript script, and if there are methods, variables and other information will be stored in it in order to use when needed. The creation of Jscontext is based on the jsvirtualmachine:-(ID) initwithvirtualmachine: (Jsvirtualmachine *) virtualmachine; if it is used-(ID) Init, Initializes a new Jsvirtualmachine object inside it and calls the initialization method in front of it.
Jsvalue can be said to be a bridge between JavaScript and Object-c, which provides a variety of ways to easily convert JavaScript data types to objective-c, or to transform the past. The following table shows the corresponding methods:
Here are some simple demos to demonstrate:
1. Basic type Conversion
*context*jsVal = [context evaluateScript:@"21+7"];int iVal = [jsVal toInt32];NSLog(@"JSValue: %@,int: %d", jsVal, iVal);
The results are as follows:
The JS variable is stored in the Jscontext and can be obtained by the bottom.
2. Array type
JSContext *context = [[JSContext alloc] init];[context evaluateScript:@"var arr = [21, 7, ‘lile.com‘];"];JSValue *jsArr = context[@"arr"];NSLog(@"JS Array:%@;Length:%@", jsArr, jsArr[@"length"]);jsArr[1] = @"blog";jsArr[7] = @7;NSLog(@"JS Array:%@;Length:%d", jsArr, [jsArr[@"length"] toInt32]);NSArray *nsArr = [jsArr toArray];NSLog(@"NSArray:%@", nsArr);
Results:
It is easy to see from the output that the code successfully assigns the data from objective-c to the JavaScript array, and Jsvalue follows the JavaScript array feature: No subscript offside, automatic extension of the array size. You can also get the properties on the JavaScript object through Jsvalue, such as the length of the JavaScript array that is obtained by "length" in the example. When it turns into a nsarray, all the information is correctly translated into the past.
3. Conversion of methods
Various data types can be converted, and objective-c blocks can also be passed into Jscontext as JavaScript methods. For example, in the front-end development of the commonly used log method, although Javascritpcore no self-contained (after all, not on the Web page, Nature will not have window, document, console these classes), You can still define a block method to invoke NSLog to simulate:
JSContext *context = [[JSContext alloc] init];context[@"log"] = ^(){ NSLog(@"**********Begin Log**********"); NSArray *args = [JSContext currentArguments]; for (JSValue *jsVal in args) { NSLog(@"%@", jsVal); } JSValue *this = [JSContext currentThis]; NSLog(@"this:%@"this); NSLog(@"**********End Log**********");};[context evaluateScript:@"log(‘ider‘, [7, 21], {hello:‘world‘, js:100});"];
The results are as follows:
The successful use of block in JavaScript calls the method back to Objective-c, and still follows the various features of the JavaScript method, such as the method parameter is not fixed. Also because of this, Jscontext provides a class method to get the argument list ( + (JSContext *) currentArguments; ) and the object that is currently calling the method ( + (JSValue *)currentThis ). For "This", the output is globalobject, which is what the Jscontext object method - (JSValue *)globalObject; returns. Because we know that in JavaScript, all global variables and methods are actually properties of a global variable, and in the browser is a window, which is unknown in JavaScriptCore.
Blocks can be passed into Jscontext as a method, but Jsvalue does not have a Toblock method to turn JavaScript into blocks for use in objetive-c. After all, the number and type of parameters and the return type of the block are fixed. Although it is not possible to extract the method, Jsvalue provides a - (JSValue *)callWithArguments:(NSArray *)arguments; way to invoke the method in turn by passing in the arguments.
[[JSContext alloc] init];[context evaluateScript:@"function add(a, b) {return a + b;}"];JSValue *add = context[@"add"];NSLog(@"Func:%@", add);JSValue *sum = [add callWithArguments:@[@(7), @(21)]];NSLog(@"Sum:%d",[sum toInt32]);
The results are as follows:
Jsvalue also provides - (JSValue *)invokeMethod:(NSString *)method withArguments:(NSArray *)arguments; methods that allow us to invoke objects directly and simply. Only if the defined method is a global function, it is clear that the method should be called on the Jscontext Globalobject object, and if it is a method on a JavaScript object, it should be called with the corresponding Jsvalue object.
4. Exception Handling
Objective-c exceptions are captured at runtime by Xcode, and JavaScript executed in Jscontext, if an exception occurs, is only captured by Jscontext and stored on the exception attribute without being thrown out. It is obviously inappropriate to check whether the exception of the Jscontext object is nil, and a more reasonable way is to set the Exceptionhandler for the Jscontext object, which accepts the ^(JSContext *context, JSValue *exceptionValue) form block. The default value is to assign the incoming Exceptionvalue to the exception property of the incoming context:
*context*exceptionValue) { context.exception = exceptionValue;};
We can also give Exceptionhandler a new block so we can immediately know when the JavaScript is running abnormally:
JSContext *context = [[JSContext alloc] init];context.exceptionHandler = ^(JSContext *con, JSValue *exception) { NSLog(@"%@"exception); con.exceptionexception;};
The results are as follows:
5. Precautions when using block
From the previous examples and presentations should have realized that block in JavaScriptCore play a powerful role, it between JavaScript and objective-c to build more bridges, make interoperability more convenient. It is important to note, however, that either the block is passed to the Jscontext object to make it a JavaScript method, or it is assigned to the Exceptionhandler property. Do not use its externally defined Jscontext object or Jsvalue directly within the block, either by passing it as a parameter to the block, or by Jscontext's class method + (Jscontext ) CurrentContext; To obtain. Otherwise, a circular reference causes the memory to not be freed properly. *
For example, the top custom exception handling method is to assign the incoming Jscontext object con, not the context object created outside, although they are actually the same object. This is because block makes strong references to internally used objects created in the external definition, and Jscontext also strongly references the given block, so that they form a circular reference (Circular Reference) that causes the memory to not be released properly.
The Jsvalue also cannot be referenced directly from outside to the block, because there are jscontext references on each jsvalue (@property (readonly, retain) Jscontext *context;), Jscontext again, a reference loop is also formed.
The front is simple, convenient and efficient, but is limited to the underlying types of numeric, Boolean, string, array, and so on. This article expands to more complex types and describes how the powerful framework enables direct interoperability of Objective-c objects and JavaScript objects.
For convenience, the Jscontext object in all of the following code will add the following log method and EventHandler:
JSContext *context = [[JSContext alloc] init];context.exceptionHandler = ^(JSContext *con, JSValue *exception) { NSLog(@"%@"exception); con.exceptionexception;};context[@"log"] = ^() {NSArray *args = [JSContext currentArguments]; forin args) { NSLog(@"%@", obj); }};
6. Key-value pair programming-dictionary
Jscontext does not allow objective-c and JavaScript objects to be converted directly, after all, the object-oriented design of the two is different: the former is based on class, the latter based on prototype. But all objects can actually be treated as a set of key-value pairs, so objects in JavaScript can be returned to OBJECTIVE-C as nsdictionary types for access.
*context*obj = [context evaluateScript:@"var jsObj = {number:7,name:‘lile‘};jsObj"];NSDictionary *dic = [obj toDictionary];NSLog(@"%@, %@", dic[@"name"], dic[@"number"]);
The results are as follows:
Similarly, nsdicionary and nsmutabledictionary can be invoked directly after they are passed into the Jscontext object:
*context = [[JSContext alloc] init]; *dic = @{@"name":@"lile"@"age":@(23)}; context[@"dic"] = dic; [context evaluateScript:@"log(dic.name, dic[‘age‘])"];
7. Language Shuttle-jsexport Protocol
JavaScript can completely define objects from prototype inheritance entirely in JSON, but objective-c programming can not be separated from classes and inherited code. So JavaScriptCore provided Jsexport as an interoperability protocol for both languages. There is no agreed method in Jsexport, not even the optional (@optional), but all the protocols that inherit the Protocol (@protocol) (Note that the method is not defined in the Objective-c Class (@interface)). Can be used in Jscontext. The language is a little bit around, or it's a little more explicit with examples.
In the. h file
#import <Foundation/Foundation.h> #import <JavaScriptCore/JavaScriptCore.h> @protocol personprotocol <jsexport>@property(nonatomic,Strong)nsdictionary*urls;-(NSString*) FullName;@end @interface Person: nsobject <personprotocol>@property(nonatomic, copy)NSString*firstname;@property(nonatomic, copy)NSString*lastname;@end
In the. m file:
#import "Person.h"@implementation Person@synthesize firstName, lastName, urls;- (NSString *)fullName { return [NSString stringWithFormat:@"%@ %@"self.firstNameself.lastName];;}@end
In the above code, a personprotocol is defined and inherited by the mysterious Jsexport protocol, which contracts the URLs attribute and the FullName method in the newly defined protocol. The person class is then defined, and the FirstName and LastName properties are defined in addition to the PERSONPROTOCOL implementation. The FullName method returns a combination of two-part names.
Here you create a person object, then pass in to Jscontext and try to access and modify the object using JavaScript.
Jscontext *context =[[Jscontext alloc]INIT];//Initialize Person objectPerson *person =[[Person alloc]Init];context[@"P"]= person;Person .FirstName = @"Li";Person .LastName = @"Le";Person .URLs = @{@"Site":@"Http://blog.csdn.net/CoderLiLe"};//OK to get fullName[Context evaluatescript:@"log (P.fullname ());"];//Cannot access FirstName[Context evaluatescript:@"log (P.firstname ())"];//OK to access dictionary as Object[Context evaluatescript:@]log ('site:', P.urls.site, 'blog:', p.urls.blog);;//OK to change URLs property[Context evaluatescript:@"p.urls = {blog: 'http://blog.csdn.net/CoderLiLe'}"];[Context evaluatescript:@"log ('---After change URLS---')"];[Context evaluatescript:@]log ('site:', P.urls.site, 'blog:', p.urls.blog);;//Affect on OBJECTIVE-C side as wellNSLog (@"%@",Person .URLs);
The results are as follows:
References:
http://justsee.iteye.com/blog/2036713
iOS7 javascriptcore.framework