目标C中可变数量的方法参数-需要一个例子 [英] Variable number of method parameters in Objective C - Need an example

查看:81
本文介绍了目标C中可变数量的方法参数-需要一个例子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自《 Objective C编程指南》 (在对象消息传递"部分下)

From Objective C Programming Guide (Under the "Object Messaging" section),

也可以采用带有可变数量参数的方法, 尽管它们很少见.多余的参数用逗号分隔 方法名称末尾之后. (与冒号不同,逗号不是 视为名称的一部分.)在下面的示例中,虚构 makeGroup:方法传递了一个必需的参数(组)和三个 可选参数:

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:

[接收者makeGroup:group,memberOne,memberTwo,memberThree];

[receiver makeGroup:group, memberOne, memberTwo, memberThree];

我试图创建这样的方法,但显示错误

I tried to create such a method and it shows an error

预期为';'方法原型之后"

"Expected ';' after method prototype"

当我尝试在接口文件(.h文件)中声明以下函数时.

when I try to declare the below function in my interface file(.h file).

- (void) printMyClass: (int) x, (int) y, (int) z;

任何人都可以举示例示例来创建类似makeGroup

Can anyone give sample example to create such a method like makeGroup

谢谢

推荐答案

您可以看到此在头文件中定义方法,在方法的末尾加三个点

In your header file define the methods with three dots at the end

-(void)yourMethods:(id)string1,...;

然后在实现文件中编写方法正文

And in you implementation file write the methods body

-(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

NOTE: remember to put nil at the end

这篇关于目标C中可变数量的方法参数-需要一个例子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆