Elias Abel Elias Abel - 5 months ago 18
iOS Question

How to pass variable parameters in objective c

this is my methods:

- (void)doSomething:(SEL)aSelector andFormatThings:(NSString *)format, ...;
- (void)justFormatThings:(NSString *)format, ...;
- (void)passDouble:(double)aDouble andFormatThings:(NSString *)format, ...;
- (void)passFloat:(float)aFloat andInt:(int)anInt andFormatThings:(NSString *)format, ...;


what I want to do is pass the parameters in the my methods (include
format
and
...
) to a method like this:

- (void)formatThings:(NSString *)format, ... {
// analysis var list and print formatted string
}


I tried to pass
va_list
to the second method but I got an error.




here's a solution:
http://stackoverflow.com/a/2391883/2284065

Answer

May be this code is helpful.

- (void)doSomething:(SEL)aSelector andFormatThings:(NSString *)format, ... 
{
    if (aSelector != NULL && [self respondsToSelector:aSelector]) 
    {
        [self performSelector:aSelector];
    }

    NSMutableArray *arr = [[NSMutableArray alloc] init];

    //store variable argument string in array
    va_list args;
    va_start(args, format);
    for (NSString *arg = format; arg != nil; arg = va_arg(args, NSString*))
    {
        [arr addObject:arg];
    }
    va_end(args);
    NSLog(@"%@",arr);

    // call - justFormatThings:
    [self justFormatThings:[arr componentsJoinedByString:@","],nil];
}
- (void)justFormatThings:(NSString *)format, ... 
{    
    NSMutableArray *arr = [[NSMutableArray alloc] init];

    //store variable argument string in array
    va_list args;
    va_start(args, format);
    for (NSString *arg = format; arg != nil; arg = va_arg(args, NSString*))
    {
        [arr addObject:arg];
    }
    va_end(args);

    NSLog(@"%@",arr);

}
-(void)tempMethod
{
    NSLog(@"Temp Method");
}

You can call doSomething:andFormatThings: like:

- (void)viewDidLoad 
{
    [super viewDidLoad];
    [self doSomething:@selector(tempMethod) andFormatThings:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",nil];

}