Objective -C - Convert UITextField text to NSUInteger

832 views Asked by At

AddSightingViewControler.h

@property (weak, nonatomic) IBOutlet UITextField *estrenoInput;

AddSightingViewControler.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([[segue identifier] isEqualToString:@"ReturnInput"]) {
        if ([self.movieTitleInput.text length] || [self.generoInput.text length] || [self.directorInput.text length]|| [self.estrenoInput.text length] )
        {
            MovieSighting *sighting;
            NSUInteger *valor = (NSUInteger *)[[self.estrenoInput text] integerValue];
            sighting = [[MovieSighting alloc] initWithName:self.movieTitleInput.text anyo:valor genero:self.generoInput.text director:self.directorInput.text];
            self.movieSighting = sighting;
        }
    }
}

I use this: NSUInteger *valor = (NSUInteger *)[[self.estrenoInput text] integerValue];

to convert it but the when I click on Done, the app exit.

Anyone did a different converter?

3

There are 3 answers

2
rmaddy On

This:

NSUInteger *valor = (NSUInteger *)[[self.estrenoInput text] integerValue];

should be:

NSUInteger valor = [[self.estrenoInput text] integerValue];
0
utahwithak On

I would say you should look into NSNumberFormatter unless you are certain they can only enter numeric values (such as a keyboard restriction). NSString's integerValue will return zero in the case of a non numeric entry. If that is ok then great, but if you need to know if the value was valid or not NSNumberFormatter numberFromString: will return nil if it was unable to convert.

Apple Docs: https://developer.apple.com/library/mac/documentation/cocoa/reference/foundation/classes/NSNumberFormatter_Class/Reference/Reference.html

0
Zach Dennis On

A good way to do this is to use NSNumber to parse the longLongValue from the string value of the textfield and then to use methods on NSNumber for the type you're interested in:

NSNumber *number = [NSNumber numberWithLongLong: textField.text.longLongValue];
NSUInteger value = number.unsignedIntegerValue;

Casting an integer to NSUInteger will only work for numeric values up to INT_MAX which will end up leaving out possible NSUInteger values (2137483648 thru 4274967295).