Is the 1st argument of an Objective C variadic function mandatory?

依然范特西╮ 提交于 2019-12-01 01:30:52

问题


Here is an example of a variadic function in Obj C.

// This method takes an object and a variable number of args
- (void) appendObjects:(id) firstObject, ...;

Is it really mandatory to have the first argument as an Obj C object? If not, what should be the syntax?

EDIT: Thanks for your responses - the first argument does not need to be an NSObject, but what I meant to ask is: Is it possible to do away with the first argument altogether? I probably did not frame the question well the first time around; sorry about that

- (void) appendObjects: ...;

The above declaration throws the following error: Expected ';' after method prototype


回答1:


It doesn't have to be anything really. There are two hidden arguments to every Objective-C method, self, and _cmd (in that order). self is self-explanatory (haha), but a lesser-known one is _cmd, which is simply the selector that was used to invoke the current method. This makes it possible to use variadic arguments with Objective-C methods seemingly without using an initial argument like you do with a standard variadic C function.

- (void) someMethod:...
{
    va_list va;

    va_start(va, _cmd);

    // process all args with va_arg

    va_end(va);
}

Then you can call the method like this:

 [someObj someMethod:1, 2, 3];



回答2:


The Objective-C way to implement variadic args is the same as in standard C. So you can pass in non-Objective-C object arguments.
Personally I'd use the first non-hidden arg to pass in the length of the following variadic list (for non-Objective-C objects - otherwise I'd use nil-termination)

- (void)appendIntegers:(NSInteger)count, ...
{
    va_list arguments;
    //the start of our variadic arguments is after the mandatory first argument    
    va_start(arguments, count);
    for(NSUInteger i = 0; i < count; ++i)
    {
        //to add the non-object type variadic arg, wrap it in a NSNumber object
        [list addObject:[NSNumber numberWithInteger:va_arg(arguments, NSInteger)]];
    }
    va_end(arguments);
    NSLog(@"%@", list);
}

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
    list = [NSMutableArray array];
    [self appendIntegers:3 /* count */, 1, 2, 3];
}



回答3:


No, it doesn’t have to be an object. You can write a variadic function taking floats, for example:

- (void) doSomethingWithFloats: (float) float1, ...;


来源:https://stackoverflow.com/questions/7357912/is-the-1st-argument-of-an-objective-c-variadic-function-mandatory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!