Literals in Objective C

Objective C is not a pure Object-Orientated language, which means you often need to convert between primitive/basic types (like char or int) and objects (like NSValue or NSNumber). This is usually rather tedious and results in large amounts of boilerplate code.

animation.fromValue = [NSNumber numberWithDouble:0.0];
animation.toValue = [NSNumber numberWithDouble:2*M_PI];

This is especially true when dealing with dictionaries – dictionaries only accept objects which means all primitive types must be boxed and unboxed. I was pleased to discover that there is a nice shorthand when dealing with these situations.

For example, the following 2 lines are equivalent.

animation.toValue = [NSNumber numberWithDouble:2*M_PI];
animation.toValue = @(2*M_PI);

Apart from wrapping an expression (as I’ve done) there is a whole list of literals available with NSNumber:

  NSNumber *letter = @'G';              // same as [NSNumber numberWithChar:'G']

  NSNumber *thirteen = @13;             // same as [NSNumber numberWithInt:13]
  NSNumber *thirteenUnsigned = @13U;    // same as [NSNumber numberWithUnsignedInt:13U]
  NSNumber *thirteenLong = @13L;        // same as [NSNumber numberWithLong:13L]
  NSNumber *thirteenLongLong = @13LL;   // same as [NSNumber numberWithLongLong:13LL]

  NSNumber *piFloat = @3.141592654F;    // same as [NSNumber numberWithFloat:3.141592654F]
  NSNumber *piDouble = @3.1415926535;   // same as [NSNumber numberWithDouble:3.1415926535]

  NSNumber *yesNumber = @YES;           // same as [NSNumber numberWithBool:YES]
  NSNumber *noNumber = @NO;             // same as [NSNumber numberWithBool:NO]

There are also literals available with arrays and dictionaries:

NSArray *animations = @[right, left, rightAgain, leftAgain];
NSDictionary *info = @{@"id" : id, @"name" : name};

While it still feels a bit clunky (especially if you’re coming from a pure object-orientated language like Ruby), it certainly makes things easier. Happy coding.

Tags: iOS, Objective-C

  1. Michael says:

    Useful tip – I didn’t know you could do this, thanks!