iOS Development Tutorial Series: Calculator Part 2

On March 8, 2011

Hello, and welcome to another iOS development tutorial. Hopefully you’ve been able to track along with me and keep pace with my teaching. If you haven’t just let me know and I can slow it down some more or explain specific concepts that you may be struggling with.

Today, we are going to proceed with our last project, the calculator. We are going to be learning some more things about object oriented programming and we are going to add some features to our calculator.

If you missed the last tutorial, I would suggest going back and reading it (here), but if you really don’t want to you can find the code from the last tutorial here.

Lets get started!

1. Open your calculator project. Go to the directory where you saved it and open the Calculator.xcodeproj file.

We are going to add a feature that will allow us to choose the operation we want to perform on our numbers, such as, addition, subtraction, multiplication, and division.

2. Open the CalculatorViewController.h (header file) and create a new IBOutlet called segmentedControl, of type, UISegmentedControl.

Now that we’ve created our outlet, lets change our interface.

3. Open up the CalculatorViewController.xib and delete the label in between our UITextFields.

So, we know what we want to happen with our application, but how can we make that happen? We are going to need some type of choosing device that will allow us to choose the operation we want to perform. To do this, we can use a UISegmentedControl, just as we declared in our header file.

4. Drag on a new object to your view called a Segmented Control.

You will want to move your textfields and output label to make your view look something similar to this:

Now we want to add new selections to the segmented control.

5. Select the segmented control on your view and then click the attributes tab in the inspector window. We are going to want to make four selections in our segmented control, so change the number of segments to four.

6. Now change each segments title to +,-,* and /.

Now, your view should look similar to this:

We nearly done in interface builder.
7. Link your segmentedControl IBOutlet to your new segmented control on your view. You should know how to do this by now and understand how it works. If you don’t then you can look at the previous tutorials.

We’re done in interface builder.

8. Hit command+s or file>save to save your progress.

Sweet! Now our interface is setup, but how do we actually use the segmented control to change between different operations? That’s easy, and something I’m about to explain.

Lets get to the code!

9. Open up the CalculatorViewController.m (implementation file).

In our segmented control we have the option to divide a number and when you divide you aren’t always guaranteed to get an whole number. As it is right now, we are using integers for our operation and an integer only returns a whole number. So in order to be able to return a decimal number we must change our variable type. We are going to change our variable type to “double” which supports numbers with a decimal place.

10. Change the variable type of all our integers to double:

double num1;

double num2;

double output;

num1 = [firstString doubleValue];

num2 = [secondString doubleValue];

We also need to change intValue to doubleValue because that would return a whole number (integer), rather than a double.

11. Change the “%d” in the line that is assigning the output to the label to “%f”.

We are doing this because %d is the format specifier for an integer, if we would have left it in there, our app wouldn’t produce the correct answer when the calculation was performed. %f is the format specifier for a double and it will produce the correct results.

So, how we are actually going to make this work, is, we check to see which value of the segmented control was selected and then we perform that action.

12. Type this above the line of code that is assigning the output to the label:

if (segmentedControl.selectedSegmentIndex == 0) {

output = num1 + num2;


if (segmentedControl.selectedSegmentIndex == 1) {

output = num1 – num2;


if (segmentedControl.selectedSegmentIndex == 2) {

output = num1 * num2;


if (segmentedControl.selectedSegmentIndex == 3) {

output = num1 / num2;


This code is pretty simple… What we are doing is, using something called an “If statement”. In this case we are using the if statement to check to see if the segmentedControl index is equal to 0, 1, 2, and 3. You would think that the first selection would be one, right? Nope, the first selection if actually zero. This isn’t very complicated and should be fairly simple to you. Although, let me explain what an index is… An index is a number representation of a position in an object. For example, if we went to the DMV and pulled a number to be waited on, the front desk knows us as that number. That is what an index is. So to sum up what we are doing, we are checking to see what was selected on our segmented control and performing our actions based upon that selection.

You may be asking yourself what the difference is between “=” and “==”. The double equals sign is saying “is equal to”, so in this case we are saying “if the selected index is equal to 0, then perform an action”. On the other hand, the single equals sign (=) is an assignment operator. For example, 2x = x + x.

We’re not moving on yet. As you’ve probably noticed, each of the operations in the if statement has a different operator in between the num1 and num2 variables. The first is obviously addition; the second, subtraction; the third, multiplication; and the fourth, division. This is a very easy concept considering these are the operators you use to do math on a computer everyday.

That’s all we needed to make the calculator function at a basic level. Go ahead and Build and Run your project and take a look at what it does.

There are a few things that we need to do though before we end this tutorial. Can you think of what might happen if we were to divide by zero? The operation would not perform. So we need to make something that will check to see if the divisor is zero, and if it is we need to display an error alert. So lets get started.

13. In your if statement for your division operation type this:

if (num2 == 0) {

UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:@”Error” message:@”You cannot divide by zero.”

delegate:self cancelButtonTitle:@”OK, I won’t do it again”


[errorAlert show];

[errorAlert release];


else {

output = num1 / num2;


What we are doing here is, we are using an if statement to check if the divisor is zero, and if it is we are creating an UIAlertView. A UIAlertView is something you see everyday on the iPhone. Here we are creating an alert and setting the title to “Error”, the text body to “You cannot divide by zero.”, the delegate to self (don’t worry about this yet),  the cancel button to “OK, I won’t do it again”, and in the last part we aren’t doing anything, but we could create other buttons there if we wanted to. After we create the alert we need to show it to the user, by calling the show method. Then we are releasing the alert after we have displayed it because we no longer need it and we want to keep good memory management on the iPhone. Before we leave the topic of AlertView we should talk a little more about it. Essentially what we are doing is calling code that Apple has already written for us (this is the basic idea of OOP). When we do this, we are calling something called a class, which is the header file and the implementation file put together. So when we are saying UIAlertView *errorAlert, we are creating an pointer called errorAlert, to that specific code that Apple has already written for us. This is some more basic OOP theory that you must understand before you can continue to learn iPhone development.

Now, notice that we are using something called an “else statement”. This statement says “If the if statement above isn’t true then perform an action”. In this instance we are saying if the divisor is zero then popup an error alert, but if it isn’t equal to zero perform an operation.

This simple “if, else statement” will keep some very bad errors out of your app.

Lets take a look and see what an alertView looks like.

14. Build and Run your project and the enter any number in the top textfield and zero in the bottom.

Sweet! Now we’ve ruled out some obvious errors that might happen with our app, but now lets explore some features of Interface builder

15. Open CalculatorViewController.xib, select your textfields, and then select the attributes tab on the inspector window.

16. Look for selector for the keyboard feature and select the number Number Pad keyboard.

17. Hit command+s or File>Save to save your progress and then Run your project.

As you can see the keyboard changed to something that is a little easier to use and this little thing will make your users much happier, since they won’t have to change the keyboard area and the search for the number they want. It’s much easier to use, and that is what iPhone apps are about (well, in Apple’s eyes).

Before we end this tutorial we need to address another error that could happen. If we were to put something other than numbers in the textfields, the operations wouldn’t perform as we wanted them to. So what we want to do, is eliminate the possibility of the users entering in data that your application can’t process. So, if we were to enter letters into the textfields something like this should happen:

We need to fix this, this is a major bug and would get your app rejected from the App Store.

18. Above the variable declarations, type:

NSString *LEGAL = @”0123456789″;

NSCharacterSet *characterSet = [[NSCharacterSet characterSetWithCharactersInString:LEGAL] invertedSet];

NSString *filteredOne = [[firstString componentsSeparatedByCharactersInSet:characterSet]


NSString *filteredTwo = [[secondString componentsSeparatedByCharactersInSet:characterSet]


firstString = filteredOne;

secondString = filteredTwo;


So, what this is doing is creating a string with the legal characters we wan’t to allow the user to enter and then we are creating something called an NSCharacterSet and putting the values of the LEGAL string into it.

Then we are creating another string and filtering the firstString string, which is the string that holds the data of the textfield. If there was anything in the firstString string other than numbers it would be removed. After we have filtered it we assign it back to the firstString and secondString strings so that the data can be processed. Pretty simple, right? Lets take a look at our work!

19. Build and run your project and enter in any character along with a number in both of the textfields.

As you can see, our code strips the strings of all other content, except the numeric data and then performs the action. This is something you want to do with all of your applications, not necessarily this specifically, but you want to remove the ability of the user to mess your application up.

We learned quite a lot in this tutorial so you may want to just read over your code and try to comprehend everything.

If you had a problem with your code or are having trouble understanding a line code, you can download my code where I offer great comments on each line about what it is doing. You can download it here.

Well, that’s it for this tutorial. Keep an eye out for the next tutorial!

If you enjoy my tutorials, you can support me by buying my app from the App Store (here). Thanks!