objective-c - Objective C 中可变数量的方法参数——需要一个例子

标签 objective-c parameters optional-parameters

来自 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/

相关文章:

c# - 也许是类和可选参数

ios - 验证 iOS 的 url 以 www 开头

iphone - UIViewController - 无法成为第一响应者

objective-c - 使用 Storyboard在 Xcode 6 os x 应用程序中更改不同的 View

c - 数组参数中的数组长度

python - 我正在寻找一种更简洁的方法来获取多个函数参数的 len

objective-c - 使用 "member"获取 Set 中的元素

javascript - 将多个参数从 ASP.NET 传递到 JavaScript 函数

c++ - 在 C++ 中通过引用传递可选参数

c++ - 带有可选参数的 boost 函数