【问题标题】:Define a method that has many (or infinite) arguments定义具有许多(或无限)参数的方法
【发布时间】:2011-08-16 14:52:39
【问题描述】:

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

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

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

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

}

【问题讨论】:

    标签: objective-c syntax arguments


    【解决方案1】:

    “无限参数”是可变参数,使用它们的方法称为可变参数方法。您定义它们的方式与您的 NSMutableArray 示例相同。 Apple 的Technical Q&A 有一个如何实现它的示例。

    - (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 参数的原因是为了让您知道何时到达列表的末尾。 NSLogprintf 之类的函数不需要最后一个参数是 nil,因为它可以计算格式字符串中的说明符数量(%d%s 等...)

    【讨论】:

    • 应该while (eachObject = va_arg(argumentList, id))while (eachObject == va_arg(argumentList, id))
    • 不,这是一个分配而不是比较。不过,我应该用一对额外的括号括起来。
    • 实现需要这么多语法垃圾的事实违背了 var arg 方法的目的。
    • 嗯,但是这些方法需要多少开销?
    猜你喜欢
    • 2011-11-06
    • 2011-01-27
    • 1970-01-01
    • 1970-01-01
    • 2022-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-25
    相关资源
    最近更新 更多