Variable number of arguments in Objective-C methods - Online Free Computer Tutorials.

'Software Development, Games Development, Mobile Development, iOS Development, Android Development, Window Phone Development. Dot Net, Window Services,WCF Services, Web Services, MVC, MySQL, SQL Server and Oracle Tutorials, Articles and their Resources

Friday, May 4, 2012

Variable number of arguments in Objective-C methods

Ever wondered how the NSString's +stringWithFormat: method work? How you can pass endless arguments in it?
Well methods that take variable arguments are known as variadic methods.

Here is an example of such a method

Declare variable argument function in your .h file as below

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.

Here is the definition in .m file –

- (void) appendObjects:(id) firstObject, ...
{
     id eachObject;
     va_list argumentList;
     if (firstObject) // The first argument isn't part of the varargs list,
     {
           [self addObject: firstObject];// so we'll handle it separately.
           va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
           while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
           {
               [self addObject: eachObject]; // that isn't nil, add it to self's contents.
           }
           va_end(argumentList); 
     }
}


I guess you came to this post by searching similar kind of issues in any of the search engine and hope that this resolved your problem. If you find this tips useful, just drop a line below and share the link to others and who knows they might find it useful too. 

Stay tuned to my blogtwitter or facebook to read more articles, tutorials, news, tips & tricks on various technology fields. Also Subscribe to our Newsletter with your Email ID to keep you updated on latest posts. We will send newsletter to your registered email address. We will not share your email address to anybody as we respect privacy.

No comments:

Post a Comment