Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 38 ยท Language Basics

Literals and Boxing

Learn Objective-C literal syntax for NSString, NSNumber, NSArray and NSDictionary, how boxing with @() works, and how to unbox values and wrap structs in NSValue.

Collections and Foundation classes only hold objects, but numbers and booleans are plain C values. To bridge the two, Objective-C offers literals that create objects directly in source code and boxing that wraps a C value in an object. Before literals arrived in 2012, creating an array of three numbers took several verbose lines. Now it takes one. This lesson covers every literal form, boxed expressions and how to take values back out.

String literals

@"text" creates an NSString. It supports the usual C escapes (\n, \t, \") and non-ASCII characters in UTF-8 source files:

OBJECTIVEC
NSString *greeting = @"Hello, \"world\"\n";
NSString *accented = @"Cafรฉ";

Plain "text" is a C string (const char *) and is not an object. Convert with NSString methods:

OBJECTIVEC
NSString *s = @(cString);                      // boxed C string, UTF-8
NSString *t = [NSString stringWithUTF8String:cString];
const char *back = [s UTF8String];

Adjacent literals are joined at compile time, which is convenient for long text: @"first " @"second".

Number literals

A suffix or form after @ creates an NSNumber:

OBJECTIVEC
NSNumber *i = @42;           // int
NSNumber *l = @42L;          // long
NSNumber *u = @42U;          // unsigned
NSNumber *f = @3.14f;        // float
NSNumber *d = @3.14;         // double
NSNumber *c = @'A';          // char
NSNumber *y = @YES;          // BOOL
NSNumber *n = @NO;

NSNumber is an immutable object wrapper for a C number. You cannot add two NSNumbers with +; unbox them first.

Boxed expressions

@( ... ) evaluates any C expression of a numeric type and boxes the result. It also boxes C strings and enum values:

OBJECTIVEC
NSNumber *sum = @(2 + 3 * 4);            // 14
NSNumber *half = @(count / 2.0);
NSNumber *level = @(ABCStatusPublished); // an enum value

Use parentheses whenever the content is not a single literal or a variable name. @count is wrong for a variable; write @(count).

Array and dictionary literals

OBJECTIVEC
NSArray *names = @[@"Ada", @"Grace", @"Linus"];
NSDictionary *person = @{
    @"name": @"Ada",
    @"age": @36,
    @"languages": @[@"Objective-C", @"C"]
};

These create immutable NSArray and NSDictionary objects. For mutable ones, copy them: [names mutableCopy]. The elements must be objects, never nil. An array literal containing nil throws an exception at run time, and so does a dictionary literal with a nil key or value. When a value might be missing, use [NSNull null] as a placeholder:

OBJECTIVEC
NSArray *row = @[@"Ada", middleName ?: [NSNull null]];

The Foundation chapter uses these collections in depth.

Subscripting

Literals pair with subscript syntax for reading and writing:

OBJECTIVEC
NSString *first = names[0];            // objectAtIndex:
NSString *name = person[@"name"];      // objectForKey:

NSMutableArray *list = [@[@1, @2] mutableCopy];
list[0] = @10;                         // replaceObjectAtIndex:withObject:
NSMutableDictionary *m = [person mutableCopy];
m[@"age"] = @37;                       // setObject:forKey:

Out-of-range indexes raise an exception, just as with the method forms.

Unboxing

To get the C value back, send a message named after the type:

OBJECTIVEC
NSNumber *n = @42;
int a = [n intValue];
NSInteger b = [n integerValue];
double c = [n doubleValue];
BOOL d = [n boolValue];

Compare numbers with isEqualToNumber: or compare:, not ==. Small integers are often tagged pointers, so @42 == @42 can be true on 64-bit Apple platforms, but that is an implementation detail you must not depend on.

Boxing structs with NSValue

Structs cannot be put into collections directly. NSValue wraps any C value, and there are convenience methods for the common geometry structs:

OBJECTIVEC
NSValue *pointValue = [NSValue valueWithPoint:NSMakePoint(3, 4)];
NSPoint back = [pointValue pointValue];

typedef struct { double x, y; } ABCVec;
ABCVec v = {1, 2};
NSValue *wrapped = [NSValue valueWithBytes:&v objCType:@encode(ABCVec)];
ABCVec out;
[wrapped getValue:&out];

@encode(type) yields a C string describing the type, which NSValue uses to check that the value is read back with the same type. For your own data, a small class is usually cleaner than NSValue.

Stand-in: what boxing really means

Boxing allocates a heap object that carries a type tag and the value. This C program models NSNumber as a tagged struct with unboxing functions. Notice that boxing an int and reading it as a double is a conversion, as in the real class.

C Stand-in (C): a tagged number box

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Stand-in: a heterogeneous collection

NSArray holds objects of any class because each is a pointer with a type tag. This C program stores boxed values in one array and processes them by checking the tag, the way isKindOfClass: would.

C Stand-in (C): array of mixed boxed values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Common mistakes

  • Writing @count instead of @(count) for variables.
  • Putting nil into an array or dictionary literal. Use [NSNull null].
  • Using + or < directly on NSNumber pointers.
  • Forgetting that literal collections are immutable; [list addObject:...] on them crashes.
  • Storing a struct in an array without NSValue.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type of object does @3.14 create?

    Numeric literals create NSNumber objects.
  2. 2. How do you box the variable count (an int)?

    Boxed expressions need parentheses, except for literal constants.
  3. 3. What happens with @[@"a", nil]?

    Collections cannot contain nil. Use [NSNull null] as a placeholder.
  4. 4. How do you read the double inside an NSNumber named n?

    Casting an object pointer does not convert it. Send doubleValue to unbox.

Summary

  • @"...", @42, @YES, @[...], @{...} and @(expr) create objects in one line.
  • Collections hold objects only: box numbers with NSNumber and structs with NSValue.
  • Literal collections are immutable, and nil is not allowed inside them.
  • Subscripts (array[0], dict[@"key"]) read and write elements.
  • Unbox with intValue, doubleValue, boolValue and so on, and compare with isEqualToNumber:.

Next: Conditionals and switch