Monday, September 17, 2012

Creating and implementing a custom method with dynamic number of arguments.

As you have noticed, there are methods which can take dynamic numbers of arguments. eg initWithObejcts:obj1,obj2,nil. This post will show you how you can create a custom method with dynamic numbers of arguments.

Here we will create a method methodWithDynamicParameters: which will take a dynamic numbers of arguments and print them on the console.

Lets proceed assuming that you have started with a project where you want to use a custom method with dynamic numbers of arguments/parameters.


Now in your header file (.h) declare the method


-(void)methodWithDynamicParameters:(id) arg1, ... ;
Here, the last three dots signifies that the methods is to accept dynamic arguments.

Now in you implementation file (.m) write the method's body

-(void) methodWithDynamicParameters:(id)arg1, ...{
    
    NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil];
    id eachObject;
    va_list argumentList;
    if (arg1) 
    {
        [arguments addObject: arg1];
        va_start(argumentList, arg1); firstObject.
        while ((eachObject = va_arg(argumentList, id)))
        {
            [arguments addObject: eachObject]; 
        }
        va_end(argumentList);
        
    }
    NSLog(@"%@",arguments);
}

Lets first go through the macros, defined in C library inside cstdarg.h file, that are used above.
va_list is used to retrieve the additional arguments of a function.
va_start : var arg list is initialized using this macro
va_arg : next arg in the list is retrieved using this macro
Va_end : this marks the end of var arg list usage

Here, a mutable array arguments to store all the arguments is created and allocated . An id object eachObject, which can hold any type of variable, is defined. Note: first argument is not the part of parameters in the args list. Therefore, it is simply stored in the array outside the scanning while loop. Then we start scanning the argument list one after another and store them to the array. (It is not necessary that you have to store those arguments in an array, I just did it for the simplicity but you can use those argument in any way you want). The while loop runs until the next argument is found nil. Then we end the use of argument list and print the array.

Now calling the function from anywhere in that class

[self methodWithDynamicParameters:@"arg1",@"arg2",@"arg3",@"arg4",nil];
NOTE: you should end the argument list with "nil".

Done! 
Now compile and run your code. So if the above code works all fine you should see an array of arguments printed in the console as below:-
(
    arg1,
    arg2,
    arg3,
    arg4
)

Suggestions and corrections are most welcome. If you have any, please do so without hesitation.




No comments:

Post a Comment