Reputation: 55604
The [NSString stringWithFormat:];
can take multiple arguments even though it's declared as NSString not NSArray and there's only one colon.
How can I have this for my own method, which is like a replacement for NSLog that writes to a text field so it's used often and I don't want to keep adding more square brackets.
Upvotes: 4
Views: 804
Reputation: 11914
Use an ellipsis after your argument name:
(NSNumber *) addValues:(int) count, ...;
You then need to use va_list
and va_start
to iterate through the arguments provided:
- (NSNumber *) addValues:(int) count, ...
{
va_list args;
va_start(args, count);
NSNumber *value;
double retval;
for( int i = 0; i < count; i++ )
{
value = va_arg(args, NSNumber *);
retval += [value doubleValue];
}
va_end(args);
return [NSNumber numberWithDouble:retval];
}
Example from: http://numbergrinder.com/node/35
Note that this is a built-in C functionality, not part of Objective-C specifically; there is a good explanation of the va_arg usage here:
http://publications.gbdirect.co.uk/c_book/chapter9/stdarg.html
Upvotes: 2