Boxed Expressions In Objective-C

September 10, 2012

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:

#define SECONDS_PER_MINUTE  60
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);

More information on Objective-C and literals:

- NSArray literals
- NSNumber literals
- NSDictionary literals