定义有很多(或无限)参数的方法 [英] Define a method that has many (or infinite) arguments

查看:171
本文介绍了定义有很多(或无限)参数的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

initWithObjects:的方法的NSArray 调用参数不确定的列表:

 的NSMutableArray *阵列= [[NSMutableArray里的alloc] initWithObjects:(ID),...,零

我如何定义我自己的方法也是这样吗?

   - (无效)CustomMethod:????? < =要采取无限参数{}


解决方案

无限论据是可变的参数,并使用它们被称为可变参数方法的方法。您可以定义它们的方式为你的的NSMutableArray 的例子一样。苹果的技术Q&安培; A 对如何实现它的例子。

   - (无效)appendObjects:(ID)firstObject,...
{
    ID eachObject;
    va_list的参数列表;
    如果(firstObject)//第一个参数是不是可变参数列表的一部分,
    {//所以我们会分开处理。
        [个体经营ADDOBJECT:firstObject];
        的va_start(参数列表,firstObject); // firstObject后启动扫描参数。
        而((eachObject =在va_arg(参数列表,ID)))//多次,我们可以得到的类型ID的参数
            [个体经营ADDOBJECT:eachObject]; //不是零,将其添加到自身的内容。
        va_end用来(参数列表);
    }
}

究其原因的说法是为了让你知道当你已经达到了列表的末尾。像的NSLog 的printf 不需要最后一个参数是,因为它可以指望(在格式字符串说明符的数量%d个%S 等。 。)

The initWithObjects: method of NSArray takes an indefinite list of arguments:

NSMutableArray *array = [[NSMutableArray alloc]initWithObjects:(id), ..., nil

How can I define my own method like this?

- (void)CustomMethod:????? <= want to take infinite arguments {

}

解决方案

The "infinite arguments" are variable arguments and the methods that use them are called variadic methods. You define them the same way as your NSMutableArray example. Apple's Technical Q&A has an example of how to implement it.

- (void) appendObjects:(id) firstObject, ...
{
    id eachObject;
    va_list argumentList;
    if (firstObject) // The first argument isn't part of the varargs list,
    {                                   // so we'll handle it separately.
        [self addObject: firstObject];
        va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
        while ((eachObject = va_arg(argumentList, id))) // As many times as we can get an argument of type "id"
            [self addObject: eachObject]; // that isn't nil, add it to self's contents.
        va_end(argumentList);
    }
}

The reason for the nil argument is so that you know when you have reached the end of the list. Functions like NSLog and printf do not require the last argument to be nil because it can count the number of specifiers in the format string (%d, %s etc...)

这篇关于定义有很多(或无限)参数的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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