I am creating a application where users will enter speeds of a car in two textFields
, Press the button
and the app will tell you which car is faster. I'm aware that in order to do so, you need to use NSNumberFormatter
but do I put the code in a separate method that compares the number and call on it when the button is clicked?
Asked
Active
Viewed 65 times
0

Dharmesh Kheni
- 71,228
- 33
- 160
- 165

Muhammad
- 109
- 1
- 9
-
Do you have `UITextField` restricted to have only integer value? – Anon Dec 13 '14 at 07:55
3 Answers
1
Try:
NSDecimal *scannerValue = [NSDecimalNumber zero];
[[NSScanner scannerWithString:[textFieldInstance stringValue]] scanDecimal:scannerValue];
if ([scannerValue decimalValue] != [NSDecimalNumber zero]) { // got a number
} else { // not a number
}
The methods available are documented here with links to the class hierarchy. If you should need further help, do leave a comment.

hd1
- 33,938
- 5
- 80
- 91
-
Hmm, what would be the benefit of using this instead of, say, using `NSCharacterSet` to validate that the text is a number and then using `floatValue`? – rebello95 Dec 13 '14 at 04:57
1
First of all you should restrict the UITextField
s for Decimal only values. Refer THIS for the same.
Then you can do something like following:
-(IBAction)fasterCar:(id)sender {
int result = [self.txtField1.text intValue]; - [self.txtField1.text intValue];
if (result > 0)
NSLog(@"1st one is faster");
else if (result < 0)
NSLog(@"2nd one is faster);
else
NSLog(@"Both cars have equal speed");
}
Might seem old school, works well.
-
i like the old school method but I am still getting an error. I have the labels declared as - (IBAction)carSpeed1:(id)sender; - (IBAction)carSpeed2:(id)sender; do i need to write arguments for these too? – Muhammad Dec 13 '14 at 23:42
-
-
but don't you need to connect the labels to the IBAction so the text changes? – Muhammad Dec 17 '14 at 23:30
0
Try like this in your button action method below:-
-(IBAction)calculateSpeed:(id)sender
{
NSDecimalNumber *first=[NSDecimalNumber decimalNumberWithString:self.txt.text];
NSDecimalNumber *second=[NSDecimalNumber decimalNumberWithString:self.txt2.text];
(second > first) ? NSLog(@"Mclaren is faster") : NSLog(@"BMW is faster");
}

Hussain Shabbir
- 14,801
- 5
- 40
- 56