Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional arguments in Objective-C 2.0?

Tags:

objective-c

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?

like image 350
willc2 Avatar asked Feb 18 '09 14:02

willc2


People also ask

How do you pass optional parameters in Objective C?

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.

Does Objective C have optionals?

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.


1 Answers

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; 
like image 168
Georg Schölly Avatar answered Oct 05 '22 05:10

Georg Schölly