如何从采用可变数量参数的method1中将可变数量的参数传递给method2? [英] How can I pass variable number of arguments to method2 from method1 that takes a variable number of arguments?

查看:110
本文介绍了如何从采用可变数量参数的method1中将可变数量的参数传递给method2?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有方法:

-(instancetype) initWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION;
+(instancetype) objWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION;

我了解如何在-initWithElements:中使用可变数量的参数,但是我不明白如何将变量从-objWithElements:传递给-initWithElements:.

I understand, how to work with variable number of arguments in -initWithElements:, but I don't understand how to pass variables from -objWithElements: to -initWithElements:.

我的意思是,我想写一些类似的东西:

I mean, I want to write something like:

+(instancetype) objWithElements:(id)firstElement, ... NS_REQUIRES_NIL_TERMINATION {
    return [[[self] initWithElements:ELEMENTS] autorelease];
}

有可能吗?

我所见问题的唯一解决方案是将参数存储在数组中,并使用将使用给定数组初始化对象的辅助方法.

The only solution for my problem I see is to store arguments in array and use helper method that will init object with given array.

推荐答案

否,在C(和Objective-C)中,无法传递可变参数.

No, in C (and Objective-C), it is not possible to pass down variadic arguments.

惯用的解决方案是让自己成为一个使用va_list的初始化程序,将那个作为指定的初始化程序,然后从其他所有方法中调用它.在可变参数方法中,它看起来像:

The idiomatic solution is to get yourself an initializer that takes a va_list, make that as the designated initializer, and then call it from every other method. From within a variadic method, this would look like:

- (instancetype)initWithVarargs:(id)first, ...
{
    va_list args;
    va_start(args, first);
    id obj = [self initWithFirst:first VAList:args];
    va_end(args);
    return obj;
}

,这是一个指定的初始化器,带有一个va_list参数:

and here's a designated initializer that takes a va_list argument:

- (id)initWithFirst:(id)first VAList:(va_list)args
{
    id obj;
    while ((obj = va_arg(args, id)) != nil) {
        // do actual stuff
    }
    // the return self, etc.
}

j

这篇关于如何从采用可变数量参数的method1中将可变数量的参数传递给method2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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