简体   繁体   English

将数组/对象从Javascript传递到Objective-C

[英]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 我的问题应该很容易回答,但是我似乎无法在Apple文档中找到任何内容

From my JS code I'm calling an Objective-C function with an array argument. 从我的JS代码中,我正在调用带有数组参数的Objective-C函数。 Eg: 例如:

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

Now in Objective-C, we have: 现在在Objective-C中,我们有:

- (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 ? 问题是:如何将这个WebScriptObject转换为NSArray

Just thought of a workaround which works fine (although it's still a workaround ) : 只是想到了一种可行的解决方法(尽管仍然是一种解决方法 ):

In JS: 在JS中:

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

In Objective-C: 在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 Javascript-> Json对象-> Objective-C-> Json对象

PS I'm sure there must be more elegant approaches (via the scarcely-documented JavaScriptCore perhaps?), but this one still does the trick! PS:我敢肯定,必须有更优雅的方法(也许通过很少记录的JavaScriptCore吗?),但是这种方法仍然有效! ;-) ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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