Trouble with WebScriptObject and interacting with arrays created in Javascript

Discussion in 'Mac Programming' started by Bunkum, Oct 30, 2011.

  1. Bunkum macrumors newbie

    Joined:
    Jun 4, 2010
    #1
    This is my first time using WebKit so I'm rather stumped with how I should be handling this problem. I want to to interact with an array in Obj-C that was created in Javascript (documentation says JS array -> Obj-C is wrapped in a WebScriptObject). But the problem is other types can be returned, so I'm not sure how I check to make sure it's an array before using "webScriptValueAtIndex:" to get the data from it.

    Since the only two ways I see you can check is going ahead with trying to access it using webScriptValueAtIndex: and just check to see if the result is WebUndefined or not. But that doesn't seem like the right way to go about it, so the other way is getting the JSObjectRef and copying it's property names and calling JSPropertyNameArrayGetCount to see if it returns a size greater than 0. So even though this seems a bit better, it isn't really telling me whether it is an array or not (e.g. could be an empty array).

    So what is the correct/suggested way to go about this?
     
  2. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #2
    The JavaScript function Array.isArray will return true if a given object is an Array object. However, there are many objects that can be used like arrays that aren't actually Array objects. For example, Array.isArray(window.frames) returns false, because window.frames doesn't result in an actual Array object, just an object that acts like an array.
     
  3. Bunkum thread starter macrumors newbie

    Joined:
    Jun 4, 2010
    #3
    I'm not having trouble with the Javascript side, but rather what's the proper way of determining if the WebScriptObject returned is an array (or any type for that matter).

    Or are you saying I should just check it in Javascript? Cause that would be another solution (and seems better than the other two), but is it the proper way to go about it?
     
  4. jiminaus macrumors 65816

    jiminaus

    Joined:
    Dec 16, 2010
    Location:
    Sydney
    #4
    Yes and no. What I'm really saying is that I don't think you can really determine this accurately on the JavaScript side or the WebScriptObject side.

    Can you be more specific about what you're dealing with? What range of return values could you get? Maybe from that we can determine an algorithm, be it in JavaScript or Objective-C.
     
  5. Bunkum thread starter macrumors newbie

    Joined:
    Jun 4, 2010
    #5
    Well for this case the function could return either an integer, or string, or object, or array. So the only real problem is checking whether it's an array or object, so just doing the check in Javascript would be fine, no?
     

Share This Page