定义具有许多(或无限)参数的方法

时间:2022-09-06 21:16:20

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

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

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

How can I define my own method like this?

我该如何定义自己的方法呢?

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

}

1 个解决方案

#1


20  

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.

“无限参数”是变量参数,使用它们的方法称为可变参数方法。您可以使用与NSMutableArray示例相同的方式定义它们。 Apple的技术问答有一个如何实现它的例子。

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

nil参数的原因是您知道何时到达列表的末尾。像NSLog和printf这样的函数不要求最后一个参数为nil,因为它可以计算格式字符串中的说明符数(%d,%s等...)

#1


20  

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.

“无限参数”是变量参数,使用它们的方法称为可变参数方法。您可以使用与NSMutableArray示例相同的方式定义它们。 Apple的技术问答有一个如何实现它的例子。

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

nil参数的原因是您知道何时到达列表的末尾。像NSLog和printf这样的函数不要求最后一个参数为nil,因为它可以计算格式字符串中的说明符数(%d,%s等...)