When communicating between JavaScript in an instance of WebView and WebViewDelegate JavaScript types and Objective-C types are converted back and forth. For example, when you call the Objective-C function from JavaScript, the string becomes NSString , the number becomes NSNumber , and the object becomes WebScriptObject .
The rest is pretty easy to handle, but WebScriptObject seems weird.
When going through a dictionary like {"foo": 1, "bar": 2} most of the code I see retrieves properties using valueForKey , for example, in [[arg valueForKey:@"foo"] intValue] == 1
But what about if you are not sure if the property exists? What if the keys are optional? [arg valueForKey:@"baz"] throws an exception.
One thing I can do is something like
@try { foo = [[arg valueForKey:@"baz"] intValue]; } @catch (NSException* e) { foo = 0; }
but I heard that exceptions from Objective-C are unsafe and should not be used to control flow.
The only other way I can think of is with a few variations of the method used here: http://edotprintstacktrace.blogspot.com/2011/10/sample-webscriptobject-javascript.html
In other words: 1. use evaluateWebScript to define a JavaScript function that implements Object.keys 2. call this function on your WebScriptObject 3. iterate over the returned array of keys and call only valueForKey if we find a match.
It seems incredibly inefficient to me. There must be a better way ... is there?
Zarel
source share