Jonathan.
Jonathan.

Reputation: 55604

string with format as argument for method (objective-c)

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

Answers (1)

GendoIkari
GendoIkari

Reputation: 11914

Use an ellipsis after your argument name:

 (NSNumber *) addValues:(int) count, ...;

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjectiveC/Articles/ocDefiningClasses.html

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

Related Questions