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];
as well as this:
[aFraction print: someParameter];
in the same program.
Apple’s Objective-C 2.0 Programming Language guide contrasts Obj-C with Python and seems to say this is not allowed. I’m still learning and I want to be sure. If it is possible, then what is the syntax, because my second code example does not work.
Update: OK, I just made two methods, both named ‘print’.
header
-(void) print; -(void) print: (BOOL) someSetting;
implementation
-(void) print { [self print:0]; } -(void) print: (BOOL) someSetting { BOOL sv; sv = someSetting; if ( sv ) { NSLog(@'cool stuff turned on'); } else { NSLog(@'cool stuff turned off'); } }
the relevant program lines
... printParamFlag = TRUE; // no parameter [aCodeHolder print]; // single parameter [aCodeHolder print:printParamFlag]; ...
I can’t believe that worked. Is there any reason I shouldn’t do this?
You can declare multiple methods:
In the implementation you can do this:
Edit:
Please do not use
printandprint: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: