Objective-c – Optional arguments in Objective-C 2.0

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?

Best Solution

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;