In Objective-C 2.0, is it possible to make a method where the argument is optional? That is, you can have a method call like this:
[aFraction print];
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:
.