来自 Objective C Programming Guide (在“对象消息传递”部分下),
Methods that take a variable number of parameters are also possible, though they’re somewhat rare. Extra parameters are separated by commas after the end of the method name. (Unlike colons, the commas are not considered part of the name.) In the following example, the imaginary makeGroup: method is passed one required parameter (group) and three parameters that are optional:
[receiver makeGroup:group, memberOne, memberTwo, memberThree];
我试图创建这样一个方法,但它显示错误
“预期‘;’在方法原型(prototype)之后”
当我尝试在我的接口(interface)文件(.h 文件)中声明以下函数时。
- (void) printMyClass: (int) x, (int) y, (int) z;
任何人都可以提供示例来创建这样的方法,例如 makeGroup
谢谢
最佳答案
可以看到这个link .
在你的头文件中定义最后三个点的方法
-(void)yourMethods:(id)string1,...;
然后在你的实现文件中写入方法体
-(void)yourMethods:(id)string1, ...{
NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil];
id eachObject;
va_list argumentList;
if (string1)
{
[arguments addObject: string1];
va_start(argumentList, string1);
while ((eachObject = va_arg(argumentList, id)))
{
[arguments addObject: eachObject];
}
va_end(argumentList);
}
NSLog(@"%@",arguments);
}
现在调用你的方法
[self yourMethods:@"ab",@"cd",@"ef",@"gf",nil];
注意:记得在末尾加上nil
关于objective-c - Objective C 中可变数量的方法参数——需要一个例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12454408/