1

Is it possible to call a function that does not specify the exact number of parameters required?

E.g. I wish to call:

-(void)genFunction:(NSString *)someID {}

and then later call it again but with a different number of parameters

-(void)genFunction:(NSString *)someID AndMore:(NSString *)anotherParam {}

I want to do this without having to write multiple functions for each case...

Best Regards Luben

1
  • 2
    To stay consistent with the common Objective-C coding practices, it is a good idea to name your methods with lowerCamelCase (no initial capital). Commented Mar 25, 2011 at 11:24

2 Answers 2

3

Yes.

You will find them in the standard framework. For example NSArray has a method:

- (id)initWithObjects:(id)firstObj, ...

the ... indicates that the method takes a variable number of arguments.

To write your own variadic methods you need to use the standard variadic functions of C, see stdarg in the documentation. The outline goes as follows:

+ (void) msgWithFormat:(NSString *)format, ...
{
    va_list args;
    va_start(args, format);
    // use the va_arg() function to access the arguments - see docs for stdarg
    va_end(args);
}

This is directly analogous to the C equivalent:

void DebugLog_Msg(const char *format, ...)
{
    va_list args;
    va_start(args, format);
    // use the va_arg() function to access the arguments - see docs for stdarg
    va_end(args);
}
Sign up to request clarification or add additional context in comments.

Comments

2

No, in Objective C parameters (or more correctly, messages) are part of the method name, Genfunction: is not related to GenFunction:AndMore: they're totally different methods.

But you could always put the common functionality in a single method and call it from the others. e.g.

- (void)genMethodByID:(NSString *)newID {
    // Your totally awesome special case.
    [self genMethod];
}

- (void)genMethodByDate:(NSDate *)newDate {
    // Your totally awesome special case.
    [self genMethod];
}

- (void)genMethod {
    // Your totally awesome common code.
}

Or just send the parameters inside NSDictionary.

- (void)genMethodWithParameters:(NSDictionary *)newDictionary {
    NSLog(@"I can haz ID: %@", [newDictionary objectForKey:@"newID"]);
    NSLog(@"I can haz date: %@", [newDictionary objectForKey:@"newDate"]);
}

2 Comments

Sorry, but you can have variadic functions in Objective-C - see next answer.
Well, to be fair, I was stating that you can't just mess up with the message, like he tried to do in his example, or you will end with a new method. The variadic is still a single message that never changes. But yeah, you're right +1.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.