Working with Boxed Expressions In Objective-C

Boxed expressions allow values to be interpreted before assigning to an object when using literals with Objective-C (see the end of post for links to more information). It’s not as confusing as it sounds, let’s look at a few examples:

The code below shows how to used a boxed expression to create a NSNumber object, calculated by multiplying to values:

int minuteCount = 50;
NSNumber *howManySeconds_NonBoxed = [NSNumber numberWithInt:
   (minuteCount * SECONDS_PER_MINUTE )];
NSNumber *howManySeconds_Boxed = @(minuteCount * SECONDS_PER_MINUTE);
NSLog(@"Total seconds: %@", howManySeconds_Boxed);

A similar idea follows using float values:

float startValue = 100000.123f;
NSNumber *floatValue = [NSNumber numberWithFloat:(startValue / 100000)];

Here is how you can wrap a boolean in a boxed expression:

NSNumber *idleTimer_NonBoxed = [NSNumber numberWithBool:[[UIApplication sharedApplication] isIdleTimerDisabled]];
NSNumber *idleTimer_Boxed = @([[UIApplication sharedApplication] isIdleTimerDisabled]);

The example below demonstrates how to use a boxed expression with a C string to create an NSString object. The C string is parsed using strpbrk to find the location of the first digit in the string. From there, the boxed expression bumps the pointer by one to point to the string following the digit.

// Get pointer to the first digit in C string
// In this example, there is a digit zero in the word f0r
const char *digitPtr = strpbrk("Check this string f0r digits", "1234567890");
// Create NSString object that represents the string ~after~ the
// first digit was found - notice the boxed expression to
// bump the char pointer to the string after the digit
NSString *strAfterDigit = digitPtr == NULL ? nil : @(digitPtr + 1);
NSLog(@"strAfterDigit: %@", strAfterDigit);

The last example is using enum type and a boxed expression to

enum {
  RemoteAccessSuccess = 200,
  RemoteAccessNotFound = 404,
  RemoteAccessError = 500,
NSNumber *fubar = @(RemoteAccessError);

Information on Objective-C Literals and Objective-C Boxed Expressions

You can read more about Objective-C Boxed Expressions in the Clang reference.

Apple has additional information about Objective-C literals in their Programming with Objective-C guide.

Following are links to tutorials on using Objective-C literals:

NSArray literals
NSNumber literals
NSDictionary literals

  1. I like that this syntax is available, but it can sometimes
    make debugging a pain. I have only too frequently seen people go
    overboard by putting too much in a boxed expression and good luck
    trying to parse that visually if you didn’t write it. In the end, I
    prefer to just break out some of these in to separate lines and
    give them temp variables, it does worlds for clarity.

    • Thanks Jason, it’s nice to see a few code examples using the __attribute__ compiler directive.

Comments are closed.