Number Parsing in Objective-C

Parsing numbers from strings is a basic but common task in many programs; here’s how to do it in Objective-C.

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // With NSNumberFormatter, we can parse floating-point numbers
        NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
        formatter.numberStyle = NSNumberFormatterDecimalStyle;
        
        NSNumber *f = [formatter numberFromString:@"1.234"];
        NSLog(@"%@", f);
        
        // For parsing integers, we can use NSString's integerValue method
        NSInteger i = [@"123" integerValue];
        NSLog(@"%ld", (long)i);
        
        // For hexadecimal numbers, we can use NSScanner
        unsigned int d;
        NSScanner *scanner = [NSScanner scannerWithString:@"0x1c8"];
        [scanner scanHexInt:&d];
        NSLog(@"%u", d);
        
        // For unsigned integers, we can use NSString's unsignedIntegerValue method
        NSUInteger u = [@"789" unsignedIntegerValue];
        NSLog(@"%lu", (unsigned long)u);
        
        // NSString's integerValue method is a convenience for basic base-10 integer parsing
        NSInteger k = [@"135" integerValue];
        NSLog(@"%ld", (long)k);
        
        // Parsing functions in Objective-C don't typically return errors.
        // Instead, they return 0 or nil for invalid input.
        NSInteger invalid = [@"wat" integerValue];
        NSLog(@"%ld", (long)invalid);
    }
    return 0;
}

In Objective-C, we use NSNumberFormatter for parsing floating-point numbers. For integers, we can use various methods provided by NSString. Here’s a breakdown of the parsing methods:

  • NSNumberFormatter is used to parse floating-point numbers.
  • integerValue method of NSString is used for parsing base-10 integers.
  • NSScanner is used for parsing hexadecimal numbers.
  • unsignedIntegerValue method of NSString is used for parsing unsigned integers.

Unlike in some other languages, Objective-C methods for parsing numbers typically don’t return errors. Instead, they return 0 or nil for invalid input.

To run the program, compile it with the Objective-C compiler and then execute:

$ clang -framework Foundation number-parsing.m -o number-parsing
$ ./number-parsing
1.234
123
456
789
135
0

Next, we’ll look at another common parsing task: URLs.