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

发布于 2024-11-30 08:49:49 字数 298 浏览 0 评论 0原文

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

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

我怎样才能像这样定义自己的方法?

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

}

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 {

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夏日浅笑〃 2024-12-07 08:49:49

“无限参数”是可变参数,使用它们的方法称为可变参数方法。您可以按照与 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);
    }
}

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文