[How To] Variable arguments in a method.

Discussion in 'iOS Development' started by gojohnnyboi, May 5, 2009.

  1. gojohnnyboi

    gojohnnyboi Well-Known Member

    Joined:
    Jan 25, 2008
    Messages:
    3,339
    Likes Received:
    55
    Hey guys. I needed to figure out (in C) today how printf() detects the variable amount of arguments when you use the placeholders like '%s' and '%d'.

    Here is how you could do it in C.

    [OBJC]void print_objects(const char *firstObject, ...) {
    va_list _arglist;
    const char *_nextobj;

    printf(firstObject);
    va_start(_arglist, firstObject);

    while(_nextobj = va_arg(_arglist, const char *)) {
    printf(_nextobj);
    }

    va_end(_arglist);
    }[/OBJC]

    this grabs all arguments after firstObject, and prints them.

    as you could imagine, it's not much different to apply this to your objective c.


    Say you wanted to extend extend the NSMutableArray class in Foundation to allow for adding multiple objects to an array in one method.

    [OBJC]#import <stdarg.h>
    #import <Foundation/Foundation.h>

    @interface tmp : NSMutableArray (VAExtension) {
    }

    - (void)addObjects

    Please Register or Log in to view images

    id)object, ...;

    @end

    @implementation NSMutableArray (VAExtension)

    - (void)addObjects

    Please Register or Log in to view images

    id)object, ... {
    id next_object;
    va_list _arglist;

    if(object != nil) {
    [self addObject

    Please Register or Log in to view images

    bject];
    va_start(_arglist, object);

    while(next_object = va_arg(_arglist, id)) {
    [self addObject:next_object];
    }

    va_end(_arglist);
    }
    }[/OBJC]

    va_list, va_arg, va_start, and va_end are declared in stdarg.h.

    thanks to Optimo for helping with this, and also the man page for stdar
  2. bddckr

    bddckr Active Member

    Joined:
    Dec 2, 2007
    Messages:
    1,434
    Likes Received:
    18
    Device:
    iPhone 4 (Black)

Share This Page