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

前端 未结 3 1445
生来不讨喜
生来不讨喜 2021-01-12 09:14

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

// This method takes an object and a variable number of args
- (voi         


        
3条回答
  •  执念已碎
    2021-01-12 09:23

    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];
    

提交回复
热议问题