Lee Lee - 6 months ago 14
Objective-C Question

Objective-c Ensure that var-arg parameters are of the correct type and count

In objective-c how do you ensure that if you have a function that takes variable parameters that the format specifiers align with the actual parameters that are passed to the functoin?

Lee Lee
Answer

This is done through the use of the NS_FORMAT_FUNCTION macro.

Let's say that you have a function like this:

LOG(int level,NSString *format,...);

The level is the log level while the format contains the format string and the variable arguments are the parameters to the format string.

In order to ensure at compile time that the count and type of the parameters is correct one defines the function as this:

LOG(int level,NSString *format,...) NS_FORMAT_FUNCTION(2,3);

Note that the 2 and 3 here refer to the position in the arguments list of the format string and the start of the variable parameter list.