The Objective-C framework introduced with iOS7 does all the heavy lifting for you. You do not need to think of objects as the same binary, but interpreted differently: when converting between ObjC and Javascript, the structure makes a copy .
From JSValue.h:
// Conversion between Objective-C and JavaScript types. // // When converting between JavaScript values and Objective-C objects a copy is // performed. Values of types listed below are copied to the corresponding // types on conversion in each direction. For NSDictionaries, entries in the // dictionary that are keyed by strings are copied onto a JavaScript object. // For dictionaries and arrays, conversion is recursive, with the same object // conversion being applied to all entries in the collection. Objective-C type | JavaScript type
For example (for simple types):
NSString *myString = [javascriptContext[@"myJSVar"] toString];
and
javascriptContext[@"myJSVar"] = myString;
or for a more complex object, use the JSExport protocol:
@protocol MyPointExports <JSExport> @property double x; @property double y; @end @interface MyPoint : NSObject <MyPointExports> // Put methods and properties not visible to JavaScript code here. @end ... javascriptContext[@"MyPoint"] = [MyPoint class]; // Define the class in Javascript
then
MyPoint *p = [javascriptContext[@"myJSPointVar"] toObject];
and
javascriptContext[@"myJSPointVar"] = p;
For each property declared in the protocol, the structure will create a JS receiver / setters, so inside Javascript you can simply do:
myJSPointVar.x = 10;
For those readers who are looking for an introduction to the JavaScriptCore framework, check out the 2013 WWDC video / pdf session “Integrating JavaScript into Native Applications” on the Apple Developer Network: https://developer.apple.com/videos/wwdc/2013/?id= 615
Mike
source share