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

前端 未结 3 1447
生来不讨喜
生来不讨喜 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:36

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

提交回复
热议问题