Assignment #1 Extra Task #3

Please note, this blog entry is from a previous course. You might want to check out the current one.

Add a +/- operation which changes the sign of the number in the display. Be careful with this one. If the user is in the middle of entering a number, you probably want to change the sign of that number and let them continue entering it, not force an enterPressed like other operations do. But if they are not in the middle of entering a number, then it would work just like any other single-operand operation (e.g. sqrt).

Add the “+/-” button in the storyboard by copying an operation button.

If the user is in the middle of entering a number, we just change the display and the history in operationPressed inside CalculatorViewController.m:

    if (self.userIsInTheMiddleOfEnteringANumber && [sender.currentTitle isEqualToString:@"+/-"]) {
        NSString *display = [self.display.text copy];
        NSString *history = [self.history.text copy];
        NSInteger lengthDisplay = [display length];
        NSInteger lengthHistory = [history length];
        if ([display hasPrefix:@"-"])
            self.display.text = [display substringFromIndex:1];
        else if ([display doubleValue])
            self.display.text = [NSString stringWithFormat:@"-%@", display];
        self.history.text = [[history substringToIndex:lengthHistory - lengthDisplay] stringByAppendingString:self.display.text];

If not we add the operator function in performOperation inside CalculatorBrain.m:

    else if ([operation isEqualToString:@"+/-"])
        result = -[self popOperand];

Flattr this!

Leave a Reply

Your email address will not be published. Required fields are marked *