Objective C 实现带有参数数组的方法
Hee
有谁知道如何在 Objective C 中实现一个方法,该方法将采用一组参数作为参数,例如:
[NSArray arrayWithObjects:@"A",@"B",nil];
该方法的方法声明是:
+ (id)arrayWithObjects:(id)firstObj...
我似乎无法自己制作这样的方法。我做了以下操作:
+ (void) doSometing:(id)string manyTimes:(NSInteger)numberOfTimes;
[SomeClass doSometing:@"A",@"B",nil manyTimes:2];
它将给出警告函数“doSometing:manyTimes:”的参数太多,
已经谢谢了。
Hee
Does anybody know how to implement an method in objective c that will take an array of arguments as parameter such as:
[NSArray arrayWithObjects:@"A",@"B",nil];
The method declaration for this method is:
+ (id)arrayWithObjects:(id)firstObj...
I can't seem to make such method on my own. I did the following:
+ (void) doSometing:(id)string manyTimes:(NSInteger)numberOfTimes;
[SomeClass doSometing:@"A",@"B",nil manyTimes:2];
It will give the warningtoo many arguments to function 'doSometing:manyTimes:'
Thanks already.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
省略号(...)继承自C;您只能将其用作调用中的最后一个参数(并且您在示例中错过了相关的逗号)。因此,在您的情况下,您可能会想要:
或者,如果您希望计数是明确的并且可以想出一种很好的措辞方式:
然后您可以使用普通的 C 方法来处理省略号,该方法位于 stdarg.h 中。 这里有一个快速文档,示例用法是:
编辑:补充,回应评论。由于 C 处理函数调用的方式(由 Objective-C 继承,尽管不是很明显),您无法将省略号中传递给您的各种内容传递给另一个采用省略号的函数。相反,您倾向于传递 va_list。例如
The ellipsis (...) is inherited from C; you can use it only as the final argument in a call (and you've missed out the relevant comma in your example). So in your case you'd probably want:
or, if you want the count to be explicit and can think of a way of phrasing it well:
You can then use the normal C methods for dealing with ellipses, which reside in stdarg.h. There's a quick documentation of those here, example usage would be:
EDIT: additions, in response to comments. You can't pass the various things handed to you in an ellipsis to another function that takes an ellipsis due to the way that C handles function calling (which is inherited by Objective-C, albeit not obviously so). Instead you tend to pass the va_list. E.g.
多个参数(也称为 arglist)只能出现在方法声明的末尾。您的
doSomething
方法将如下所示:调用方式如下:
另请参阅:如何在 Objective-C 中创建可变参数方法
Multiple arguments (also known as an arglist) can only come at the end of a method declaration. Your
doSomething
method would look something like this:To be called as follows:
See also: How to create variable argument methods in Objective-C
我认为您正在追求可变参数函数。这是苹果的文档: http://developer.apple.com/library/mac /qa/qa2005/qa1405.html
I think you're after a variadic function. Here's Apple's documentation: http://developer.apple.com/library/mac/qa/qa2005/qa1405.html