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?
Methods in Objective C are actually called messages but they're often referred to as methods, a more commonly used terminology. Optional parameters are treated in an interesting way in Objective C. Basically there are no optional parameters! In fact the parameters help to define the method.
It is common in Objective-C to return nil for an object reference where in Swift you would use an optional type. Unfortunately there is nothing in the Objective-C code that tells the compiler which references can be nil so it assumes the worst and makes everything an implicitly unwrapped optional.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With