开发者

Exposing Objective-c object to JavaScript environment in JSON format

I want to represent any objective-c object in JSON format at RUNTIME, so that a javascript script can use it to access any field/variables/properties through 'dot' notation.

For example,

Objec开发者_运维知识库tive-c class for the object could be:

@interface myNativeObject 
   PrimtivieType *pVar;
   CustomClassType *cVar;
@end

Where CustomClassType may contain another object as shown below:

@interface CustomDataType
  PrimitiveType *myVar;
@end

I want to Expose myNativeObject to JavaScript in JSON format, as follows:

    var nativeObjInJavaScript = {
                                  pVar:pval,
                                  cVar:{
                                         myVar:myVarValue
                                  }
                                }

So, now following JavaScript expression shoule work correctly:

var LValue = nativeObjInJavaScript.cVar.myVar;

I am thinking of

1.) writing a recursive function which will use Objective-C runtime library to get information about the object and generate the JSON equivalent. Am I on the right track?

2.) Key-Value encoding feature of Objective-c could be of any help in this case?

Regards,


On OS X, WebKit has the mechanism already, read this document. You just need to get the window script object and set your Obj-C object there:

 WebScriptObject* wso=[webView windowScriptObject];
 [wso setValue:objCobj forKey:@"javascriptName"];

You need to specify the method names and properties accessible from the javascript side in

 + (BOOL)isSelectorExcludedFromWebScript:(SEL)aSelector;
 + (BOOL)isKeyExcludedFromWebScript:(const char *)name;

of the class you expose.

On iPhone, the method you can use on UIWebView is stringByEvaluatingJavascriptFromString: to construct the javascript object, and the delegate method webView:shouldStartLoadWithRequest:navigationType: to receive the info back. If you want to expose generic objects you need to use approach 1), but I don't think that's generically good; NSObject can have lots of private ivars which are picked up by the runtime, which you might not want to expose. I guess it's better to give the list of properties you want to expose.

The project PhoneGap heavily uses this technique, so reading its source code might help you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜