如何使用适用于iOS的phonegap插件将数组作为参数传递给函数

时间:2011-07-25 06:43:01

标签: javascript objective-c ios plugins cordova

我正在为iOS编写一个phonegap插件。   在 javascript文件中,我需要将一些数组传递给我的函数。但是,在 .m 文件中, [arguments count] 仅显示我传递给我的函数的'字符串'参数的数量。这意味着,传递给我的函数的数组不会在.m文件中被理解/看到。

以下是senario:

 In test.js, I call test() function with 2 arrays and 1 string. 
 In MyPlugin.m, in test() function, however, the number of arguments shown is only 1.

----------- plugin.js --------------------
function MyPlugin(){
};

MyPlugin.prototype.test = function(arg1, arg2, arg3){
   PhoneGap.exec('MyPlugin.test', arg1, arg2, arg3);
}

//.....code is omitted......
------------------------------------------

---------------declare plugin----------------
function onDeviceReady() {
   myPlugin = window.plugins.plugin;
}
--------------------------------------------------

-----------test.js where function is called----------------
function testPlugin(){
   var arr1 = new Array(),
        arr2 = newArray(),
        text = 'sample string';
   myPlugin.test(arr1, arr2, text);
};
-----------------------------------------------------------------------

--------------MyPlugin.m--------------------------
-(void)test:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options
{
   NSUInteger argc = [arguments count];
   NSLog(@"Number of arguments: %d", argc);     //output: Number of arguments: 1

   NSString *text = [arguments objectAtIndex:0]; 
   NSLog(@"%@", text);   //output: sample string
}
---------------------------------------------------------

所以我的问题是如何将数组传递给iOS的phonegap插件中的javascript函数。

由于

2 个答案:

答案 0 :(得分:0)

我对这个问题的解决方案是我对数组进行字符串化,然后将它们作为字符串传递给函数。然后在.m文件中,我将这些字符串解析为数组。

解决了这个问题。但是,如果您知道任何其他解决方案,请建议。

谢谢,

答案 1 :(得分:0)

我偶然发现了同样的问题,并在此处找到了另一种解决方案:

https://groups.google.com/forum/?fromgroups#!topic/phonegap/Agy_9r_7FAc

从cordova.exec函数传递到本机iOS代码的对象/数组存储在options数组参数中。诸如字符串,整数等常规参数存储在arguments数组参数中。