views:

22

answers:

1

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,

Objective-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,

A: 

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.

Yuji
Yuji - I want to achieve this on iPhone hence "WebScriptObject" will not be useful for sure. Anyways, thanks for your response. I will look into the PhoneGap source code and will try to write recursive function which can selectively expose desired properties/vars. Thanks.
Mehul Patel