iOS Dev – Assignment #2 – Task #1

Model-View-Controller Since a calculator is something that might be used in various situations, you decide to rewrite your code to something more reusable. One advantage of MVC is that you can exchange the view but keep your model and parts of your controller. We provide you with a template for a class called BasicCalculator. Extend that class to provide a fully functional basic calculator. This class is your model.

The provided template is similar to the one from Assignment #1, where the calculator functionality is moved to the new model class. You could either use your code from the previous assignment and adjust it or redo the changes from the previous assignment inside the new template. Here we will choose the second approach.

First link the missing number buttons to the view controller class and change the tags of the buttons accordingly.

Add the method for the pressed comma button and link it (note that the following code is much simpler as before because we are asked to check for double commas in the next task and do not want to jump ahead 😉 ):

- (IBAction)commaPressed:(UIButton *)sender {
    self.numberTextField.text = [self.numberTextField.text stringByAppendingString:@"."];
}

Link the missing operation buttons to the view controller class and change the missing tag. However where we before have defined the buttons functionality with constants we now define a type with the values from the tags in the header file of the new calculator class:

typedef enum BCOperator : NSUInteger {
	BCOperatorNoOperation,
	BCOperatorAddition = 11,
	BCOperatorSubtraction = 12,
	BCOperatorMultiplication = 13,
	BCOperatorDivision = 14
} BCOperator;

Finally add the missing calculator functions to (for now) the view controller class:

- (float)executeOperation:(BCOperator)operation 
             withArgument:(float)firstArgument 
        andSecondArgument:(float)secondArgument 
{
        switch (operation) {
                ...
        case BCOperatorMultiplication:
            return firstArgument * secondArgument;
        case BCOperatorDivision:
            if (!secondArgument) return NAN;
            return firstArgument / secondArgument;
        default:
            return secondArgument;
            break;
	}
}

Actually we have not really done anything MVC yet, and the calculator has less features then the old one …

Facebooktwittergoogle_plusredditpinterestlinkedintumblrmailFacebooktwittergoogle_plusredditpinterestlinkedintumblrmail

Flattr this!

Leave a Reply

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