简体   繁体   中英

Pass array/object from Javascript to Objective-C

My question should be fairly simple to answer, but I can't seem to find anything in Apple's documentation

From my JS code I'm calling an Objective-C function with an array argument. Eg:

ObjC.someFunction_([1,2,3]);

Now in Objective-C, we have:

- (void)someFunction:(WebScriptObject*)arr
{

}

As Apple suggests. (If it was a simple string then that's a whole different - and much simpler - story).

The question is: HOW do I convert this WebScriptObject into an NSArray ?

Just thought of a workaround which works fine (although it's still a workaround ) :

In JS:

ObjC.someFunction_(JSON.stringify([1,2,3]));

In Objective-C:

- (void)someFunction:(NSString*)arrStr
{
    NSArray* arr = [NSJSONSerialization JSONObjectWithData:[arrStr dataUsingEncoding:NSUTF8StringEncoding] 
                                                   options:kNilOptions 
                                                     error:nil];
}

In a schematic diagram:

  • Javascript -> Object to Json -> Objective-C -> Json to Object

PS I'm sure there must be more elegant approaches (via the scarcely-documented JavaScriptCore perhaps?), but this one still does the trick! ;-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM