Objective C的实现方法,需要的参数数组 [英] Objective c implement method which takes array of arguments

查看:153
本文介绍了Objective C的实现方法,需要的参数数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有人知道如何实现目标C的方法,将采取的参数数组作为参数,如:

Does anybody know how to implement an method in objective c that will take an array of arguments as parameter such as:

[NSArray arrayWithObjects:@"A",@"B",nil];

此方法的方法声明为:

The method declaration for this method is:

+ (id)arrayWithObjects:(id)firstObj...

我似乎无法做出这样的方法我自己。我做了以下内容:

I can't seem to make such method on my own. I did the following:

+ (void) doSometing:(id)string manyTimes:(NSInteger)numberOfTimes;

[SomeClass doSometing:@"A",@"B",nil manyTimes:2];

这会给warningtoo许多争论的功能'doSometing:manyTimes:

It will give the warningtoo many arguments to function 'doSometing:manyTimes:'

谢谢了。

推荐答案

省略号(...)是从C继承;你可以用它只能作为在通话的最后一个参数(你已经错过了你的榜样相关的逗号)。因此,在你的情况下,你可能想:

The ellipsis (...) is inherited from C; you can use it only as the final argument in a call (and you've missed out the relevant comma in your example). So in your case you'd probably want:

+ (void)doSomethingToObjects:(id)firstObject, ...;

或者,如果你想计数是明确的,能想到的措辞很好的一种方式:

or, if you want the count to be explicit and can think of a way of phrasing it well:

+ (void)doManyTimes:(NSInteger)numberOfTimes somethingToObjects:(id)firstObject, ...;

您就可以使用普通的C方法处理椭圆,它驻留在STDARG.H。这里有那些的快速文档,例如用法是:

You can then use the normal C methods for dealing with ellipses, which reside in stdarg.h. There's a quick documentation of those here, example usage would be:

+ (void)doSomethingToObjects:(id)firstObject, ...
{
    id object;
    va_list argumentList;

    va_start(argumentList, firstObject);
    object = firstObject;

    while(1)
    {
        if(!object) break; // we're using 'nil' as a list terminator

        [self doSomethingToObject:object];
        object = va_arg(argumentList, id);
    }

    va_end(argumentList);
}

编辑:添加,响应于注释。你不能交给你的省略号到另一个函数,它接受一个省略号的各种事情,由于传递和C语言处理函数调用(这是由Objective-C的继承,尽管不是很明显的话)的方式。相反,你往往会通过va_list的。例如。

additions, in response to comments. You can't pass the various things handed to you in an ellipsis to another function that takes an ellipsis due to the way that C handles function calling (which is inherited by Objective-C, albeit not obviously so). Instead you tend to pass the va_list. E.g.

+ (NSString *)doThis:(SEL)selector makeStringOfThat:(NSString *)format, ...
{
    // do this
    [self performSelector:selector];

    // make string of that...

    // get the argument list
    va_list argumentList;
    va_start(argumentList, format);

    // pass it verbatim to a suitable method provided by NSString
    NSString *string = [[NSString alloc] initWithFormat:format arguments:argumentList];

    // clean up
    va_end(argumentList);

    // and return, as per the synthetic example
    return [string autorelease];
}

这篇关于Objective C的实现方法,需要的参数数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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