views:

30

answers:

2

How do you create a method in Objective-C that accepts a NSString format (using the comma seperated list list of arguments to substitute into the format). Something like:

// Hello Kevin
NSString *name = @"Kevin";
[NSString stringWithFormat:@"Hello %@", name];
+4  A: 

What you're looking for is called a Variadic Function and in Objective-C you can write something like the following:

- (NSString *) stringWithFormat:(NSString ) format, ... { }

You can use this excellent example for Objective-C variadic functions for more detail.

Gavin Miller
Awesome! Thanks, couldn't find it cause I didn't know the name for it. Very helpful!
Kevin Sylvestre
+1  A: 

These are variadic arguments.

@interface Foo {}
-(void)myVariadicMethod:...;
@end

@implementation Foo

-(void)myVariadicMethod:...
{
 va_list arguments;
    // _cmd is a hidden argument all Objective-C methods receive
 va_start(arguements, _cmd);

 // same as for a C function: use va_arg

 va_end(arguments);
}

@end

The ellipsis must always be the last "argument" your method accepts.

zneak
Thanks for the great example! Appreciate the help!
Kevin Sylvestre