TExcelTAD
Home › Objective-C › NSNumber & Literals

NSNumber & Literals

Foundation's collections (NSArray, NSDictionary, NSSet) can only hold objects, not C values like int or double. NSNumber boxes a number (or a BOOL) into an object so it can be stored in a collection, compared and printed with %@.

Creating NSNumbers

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // The long way: class factory methods
        NSNumber *a = [NSNumber numberWithInt:42];
        NSNumber *b = [NSNumber numberWithDouble:3.5];
        NSNumber *c = [NSNumber numberWithBool:YES];

        // The modern way: @ literals
        NSNumber *d = @42;
        NSNumber *e = @3.5;
        NSNumber *f = @YES;
        NSNumber *g = @'Z';      // a char

        NSLog(@"%@ %@ %@", a, b, c);
        NSLog(@"%@ %@ %@ %@", d, e, f, g);
    }
    return 0;
}
42 3.5 1
42 3.5 1 90

@YES prints as 1 because a boxed BOOL is a number, and @'Z' prints 90, the character's code: an NSNumber stores the numeric value, not the letter.

Boxed expressions

Put any C expression in @( … ) to box its result. This is how you box variables:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        int width = 8;
        int height = 5;
        double ratio = (double)width / height;

        NSNumber *area = @(width * height);
        NSNumber *boxedRatio = @(ratio);
        NSNumber *isWide = @(width > height);

        NSLog(@"area %@, ratio %@, wide %@", area, boxedRatio, isWide);

        // @( ) also boxes C strings into NSStrings
        const char *cName = "boxed";
        NSString *name = @(cName);
        NSLog(@"%@ has length %lu", name, (unsigned long)name.length);
    }
    return 0;
}
area 40, ratio 1.6, wide 1
boxed has length 5

@width (without parentheses) is not allowed: literals only work with constant numbers, so use @(width).

Unboxing

To do arithmetic, take the C value out again with one of the …Value methods:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *prices = @[@4.5, @12, @0.99];
        double total = 0;
        for (NSNumber *price in prices) {
            total += [price doubleValue];
        }
        NSLog(@"total: %.2f", total);

        NSNumber *n = @7.9;
        NSLog(@"intValue %d, doubleValue %.1f, boolValue %d", n.intValue, n.doubleValue, n.boolValue);
        NSLog(@"integerValue of @3: %ld", (long)[@3 integerValue]);
        NSLog(@"stringValue: %@", [@250 stringValue]);
    }
    return 0;
}
total: 17.49
intValue 7, doubleValue 7.9, boolValue 1
integerValue of @3: 3
stringValue: 250

intValue on 7.9 truncates to 7; it doesn't round.

Method Returns
intValue, integerValue, longLongValue integers
unsignedIntegerValue NSUInteger
doubleValue, floatValue floating point
boolValue BOOL
stringValue an NSString

Comparing numbers

NSNumber compares by value, across different underlying types:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSNumber *intTen = @10;
        NSNumber *doubleTen = @10.0;
        NSNumber *five = @5;

        NSLog(@"isEqualToNumber: %d", [intTen isEqualToNumber:doubleTen]);
        NSLog(@"isEqual: %d", [intTen isEqual:doubleTen]);
        NSLog(@"compare 10 vs 5: %ld", (long)[intTen compare:five]);
        NSLog(@"compare 5 vs 10: %ld", (long)[five compare:intTen]);

        if ([five compare:intTen] == NSOrderedAscending) {
            NSLog(@"5 comes before 10");
        }
    }
    return 0;
}
isEqualToNumber: 1
isEqual: 1
compare 10 vs 5: 1
compare 5 vs 10: -1
5 comes before 10

Note: Don't compare NSNumbers with == or <. == compares pointers, and < on pointers compares memory addresses: both compile but give meaningless results.

Collection literals

The same @ syntax creates arrays and dictionaries, which you'll study in the next lessons:

objc · try it yourself
#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        NSArray *scores = @[@90, @75, @(80 + 8)];
        NSDictionary *player = @{@"name": @"Zoe", @"level": @12, @"premium": @YES};

        NSLog(@"first score: %@", scores[0]);
        NSLog(@"%@ is level %@", player[@"name"], player[@"level"]);
        NSLog(@"premium: %d", [player[@"premium"] boolValue]);
    }
    return 0;
}
first score: 90
Zoe is level 12
premium: 1
Literal Creates
@"text" NSString
@42, @3.5, @YES, @'c' NSNumber
@(expression) NSNumber (or NSString from a C string)
@[a, b, c] NSArray
@{key: value} NSDictionary

NSDecimalNumber for money

double can't represent most decimal fractions exactly (0.1 + 0.2 isn't exactly 0.3). For money, use NSDecimalNumber, a subclass of NSNumber that does base-10 arithmetic:

objc
NSDecimalNumber *price = [NSDecimalNumber decimalNumberWithString:@"0.10"];
NSDecimalNumber *tax   = [NSDecimalNumber decimalNumberWithString:@"0.20"];
NSDecimalNumber *sum   = [price decimalNumberByAdding:tax];   // exactly 0.3

Integer cents (an NSInteger of 1999 for $19.99) are an even simpler alternative.

Test yourself

Why do we need NSNumber?

  1. C numbers are too slow
  2. Collections can only store objects
  3. NSLog can't print ints
  4. To use more than 64 bits

How do you box the int variable count?

  1. @count
  2. @(count)
  3. [count box]
  4. NSNumber(count)

What does [@7.9 intValue] return?

  1. 8
  2. 7
  3. 7.9
  4. 0