Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to safely read properties of a WebScriptObject?
    primarykey
    data
    text
    <p>When communicating between JavaScript in a <code>WebView</code> instance and a <code>WebViewDelegate</code>, JavaScript types and Objective-C types are converted back and forth. For instance, when calling an Objective-C function from JavaScript, a string becomes an <code>NSString</code>, a number becomes an <code>NSNumber</code>, and an Object becomes a <code>WebScriptObject</code>.</p> <p>The others are pretty simple to deal with, but <code>WebScriptObject</code> seems weird.</p> <p>When passing a dictionary like <code>{"foo": 1, "bar": 2}</code>, most of the code I see extracts the properties using <code>valueForKey</code>, such as in <code>[[arg valueForKey:@"foo"] intValue] == 1</code></p> <p>But what about if you're not sure if the property exists? What if the keys are optional? <code>[arg valueForKey:@"baz"]</code> throws an exception.</p> <p>One thing I can do is something like</p> <pre><code>@try { foo = [[arg valueForKey:@"baz"] intValue]; } @catch (NSException* e) { foo = 0; } </code></pre> <p>but I've heard that exceptions in Objective-C are unsafe and should not be used for flow control.</p> <p>The only other way I can think of is some variation of the method used here: <a href="http://edotprintstacktrace.blogspot.com/2011/10/sample-webscriptobject-javascript.html">http://edotprintstacktrace.blogspot.com/2011/10/sample-webscriptobject-javascript.html</a></p> <p>In other words: 1. use <code>evaluateWebScript</code> to define a JavaScript function that implements <code>Object.keys</code> 2. call that function on your <code>WebScriptObject</code> 3. iterate through the returned array of keys, and only call <code>valueForKey</code> if we find a match.</p> <p>This seems incredibly inefficient, to me. There must be a better way... is there?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload