Converting between Strings and Numbers

When programming for iPhone or iPad, we often need to get input from the user. This input usually comes from Text Fields as an NSString type. If the input is numeric, we will need to convert the string to a numeric type before working with it. Let’s see how this is done.

Start Xcode, and select “Create a new Xcode project.” Choose the Single View Application template and click Next. Name the project “Number2String” and choose options as shown below:

Click Next, choose a location to save the project, and finally click Create.

We’ll begin by configuring the .zib file for the user interface. Drag four labels, two text fields, and a button to the view. Your interface should look something like the one shown to the right. We’ll wire up these controls shortly, but first let’s talk about what will happen as the program runs.

When the user touches one of the text fields, they will see the keyboard. As they enter a value into the field, the text property of the UITextField will be updated with an NSString type. We can read the value of this string by looking at this property, but if we want to add the values in the two fields, we must first covert them to numeric types.

The “Add” button (through it’s IBAction method) will do the work of converting the two NSStrings from the UITextFields into floating point numbers. It will then add them together. But in order to display the sum in the last UILabel, it will have to convert the sum back into a string.

Open ViewController.h, and make the changes shown here:

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UITextField *num1;
@property (nonatomic, strong) IBOutlet UITextField *num2;
@property (nonatomic, strong) IBOutlet UILabel *sum;

(IBAction)addButtonTouched:(UIButton *)sender;
(IBAction)dismissKeyboard:(UITextField *)sender;

@end

As you can see, we’ve added three IBOutlet properties, two for the UITextFields and one for the UILabel that will display the sum. We’ve also added two action methods: the addButtonTouched method will add the two numbers and display the result, and the dismissKeyboard method will make the keyboard go away when its “Done” button is touched. Make sure to set the return key type on both UITextFields to “Done” in the .zib file.

Wire up the outlets and actions as shown:

Note that the addButtonTouched action is wired to the Add button’s TouchUpInside event and the dismissKeyboard action is wired to each text field’s DidEndOnExit event. Num1 and num2 are wired to the UITextFields, and sum is wired to the last UILabel on the view.

Now open up ViewController.m, and make these changes:

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize num1, num2, sum;

(IBAction)addButtonTouched:(UIButton *)sender
{
    float num1f = [num1.text floatValue];
    float num2f = [num2.text floatValue];
    float sumf  = num1f + num2f;
    self.sum.text = [NSString stringWithFormat:@"%f", sumf];
}

(IBAction)dismissKeyboard:(UITextField *)sender
{
    [self.num1 resignFirstResponder];
    [self.num2 resignFirstResponder];
}

(void)viewDidLoad
{
    [super viewDidLoad];
        // Do any additional setup after loading the view, typically from a nib.
}

(void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    self.num1 = nil;
    self.num2 = nil;
    self.sum  = nil;
}

(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

@end

First, we synthesize the properties num1, num2, and sum. Next, we define the two action methods. In the addButtonTouched method, we can see the conversion from a string to a number taking place in these two lines:

float num1f = [num1.text floatValue];
    float num2f = [num2.text floatValue];

we get the floating point value of an NSString by sending the floatValue class method to it as shown above. To obtain an int value, we would send the intValue method. (We could also get an NSInteger by sending the integerValue method to the string.) These floating point values are assigned to local variables within the addButtonTouched method.

In the next line, the values are added into a new float variable named sum. The sum is then displayed in the UILabel *sum using the stringWithFormat class method.

By the way, when we use a class method to obtain an object (as with stringWithFormat), that object will be automatically released for us. This is because there are no strong references to the object. The general rule is if we don’t use alloc, copy, or new to get an object, there will be no strong reference, and we don’t have to worry about the memory associated with the object.

The dismissKeyboard method simply calls resignFirstResponder on both UITextField controls. There is another blog in this series that discusses this process in detail.

When the program is run, we see the following results:

Note that the value obtained is not quite 32.3 as we would expect. This has to do with the precision of the floating point result, not with a defect of our program. The precision error can be dealt with by other means (rounding to a desired number of decimal places is the usual approach).

Take time to play around with various formatting specifiers in the stringWithFormat method, and also try intValue instead of floatValue (assigning the results to ints instead of floats). Have fun!

Leave a Reply

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