Tuesday, October 18, 2011

Matt Gallagher: Variable argument lists in Cocoa

Itt van, de ami nekem kellett azt bemasolom:

The va_list, va_start, va_arg and va_end are all standard C syntax for handling variable arguments. To describe them simply:

  • va_list - A pointer to a list of variable arguments.
  • va_start - Initializes a va_list to point to the first argument after the argument specified.
  • va_arg - Fetches the next argument out of the list. You must specify the type of the argument (so that va_arg knows how many bytes to extract).
  • va_end - Releases any memory held by the va_list data structure.

Generally speaking, you can use this for loop for any variable argument situation where your arguments are all the same type. Other cases are a bit trickier but far less common — I'm sure you can work out how they would work if needed.

va_list in Cocoa

A number of classes in Cocoa have methods that take variable numbers of arguments. In most cases, these classes will also have an equivalent method that takes a va_list.

We can see an example of these va_list equivalents by looking at NSString. NSString declares the class method stringWithFormat:... (which takes a variable number of arguments) andNSString also declares the instance method initWithFormat:arguments: (where the argumentsparameter is a va_list) which handles the equivalent behavior of stringWithFormat:....

These va_list methods are used in the situation where your class defines a method with a variable argument list and you need to pass those variable arguments into the Cocoa method. For example, if the StringContainer class listed above declared the method:

- (void)setContentsWithFormat:(NSString *)formatString, ...;

The implementation of this method would be as follows:

- (void)setContentsWithFormat:(NSString *)formatString, ...
{
[contents autorelease];
va_list args;
va_start(args, formatString);
contents = [[NSString alloc] initWithFormat:formatString arguments:args];
va_end(args);
}

The va_list parameter allows us to pass our own variable argument list to the Cocoa method so that the Cocoa method can handle the arguments.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.