Optional arguments in Objective-C 2.0?
Solution 1:
You can declare multiple methods:
- (void)print;
- (void)printWithParameter:(id)parameter;
- (void)printWithParameter:(id)parameter andColor:(NSColor *)color;
In the implementation you can do this:
- (void)print {
[self printWithParameter:nil];
}
- (void)printWithParameter:(id)parameter {
[self printWithParameter:nil andColor:[NSColor blackColor]];
}
Edit:
Please do not use print
and print:
at the same time. First of all, it doesn't indicate what the parameter is and secondly no one (ab)uses Objective-C this way. Most frameworks have very clear method names, this is one thing that makes Objective-C so pain-free to program with. A normal developer doesn't expect this kind of methods.
There are better names, for example:
- (void)printUsingBold:(BOOL)bold;
- (void)printHavingAllThatCoolStuffTurnedOn:(BOOL)coolStuff;
Solution 2:
The way you did it is the right way to do it in Objective-C. It's used extensively in Cocoa itself. For example, some of NSString's initializers:
– initWithFormat:
– initWithFormat:arguments:
– initWithFormat:locale:
– initWithFormat:locale:arguments:
The reason it works is because the :
is part of the method name, so as far as the compiler is concerned, print
and print:
are completely different messages that are no more closely connected than "print" and "sprint".
However, the particular names of the methods you gave aren't a very good case for this, because it's unclear from the name what the parameter is (or what "print" by itself means if the parameter is what the object prints). It would be better to have, say, printFalseMessage
and printMessageWithFlag:
.
Solution 3:
Another option for multiple optional arguments is to pass them all in an NSDictionary:
- (void)someMethodWithOptions:(NSDictionary *)options;
then declare that the options dictionary may contain:
- key1, value must be a BlahObject
- key2, value must be a NonBlahObject
you can then allow any of the keys to be absent and even the dictionary itself could be nil.