typestar

NSNumber boxing in Objective-C

@() lifts C values into objects; unboxing is one accessor each.

#import <Foundation/Foundation.h>

int main(void) {
    @autoreleasepool {
        // @() boxes C values into NSNumber objects for collections.
        NSNumber *year = @(1959);
        NSNumber *price = @(24.99);
        NSNumber *sealed = @YES;

        NSArray<NSNumber *> *pressing = @[ year, price, sealed ];
        NSLog(@"Boxed: %@", [pressing componentsJoinedByString:@" | "]);

        // Unboxing is explicit, one accessor per C type.
        NSInteger y = [year integerValue];
        double p = [price doubleValue];
        NSLog(@"%ld pressing at %.2f, sealed: %d",
              (long)y, p, [sealed boolValue]);
    }
    return 0;
}

How it works

  1. @(1959), @(24.99) and @YES box int, double, and BOOL.
  2. Boxed numbers ride in collections like any object.
  3. integerValue and friends unbox back to C types.

Keywords and builtins used here

The run, in numbers

Lines
20
Characters to type
542
Tokens
108
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 100 seconds.

Type this snippet

Step 1 of 3 in C interop, step 22 of 27 in Language basics.

← Previous Next →