Last week I wrote about NSArray Literals in Objective-C. This week I will show you how to use NSNumber literals. To use literals, you will need to be running Xcode 4.4 or greater as well as the Apple LLVM compiler 4.0 or greater.
Just as a string literal is prefixed with an ‘@’ symbol:
NSString *str = @"This is a string";
you can now create NSNumber objects using literals. A range of examples follow, showing the old style definition as well as the new literal syntax:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Float literal NSNumber *floatNumberOld = [NSNumber numberWithFloat:999.99f]; NSNumber *floatNumberNew = @999.99; // Double literal NSNumber *piOld = [NSNumber numberWithDouble:3.1415926535]; NSNumber *piNew = @3.1415926535; // Integer literal NSNumber *intNumberOld = [NSNumber numberWithInt:99]; NSNumber *intNumberNew = @99; // Unsigned integer literal NSNumber *unsignedIntNumberOld = [NSNumber numberWithUnsignedInt:999]; NSNumber *unsignedIntNumberNew = @999; // Long integer NSNumber *longNumberOld = [NSNumber numberWithLong:1212l]; NSNumber *longNumberNew = @121212l; // Long long integer NSNumber *longLongNumberOld = [NSNumber numberWithLongLong:2323232323ll]; NSNumber *longLongNumberNew = @2323232323ll; // Boolean literal NSNumber *booleanNumberOld = [NSNumber numberWithBool:YES]; NSNumber *booleanNumberNew = @YES; NSNumber *booleanNumberNew = @(YES); // Charater literal NSNumber *charNumberOld = [NSNumber numberWithChar:'A']; NSNumber *charNumberNew = @'A';
On line 28 I show an alternative that you may need to use depending on which version of Xcode and the compiler you are running. If you get the error: unexpected type name ‘BOOL’: expected expression, add the parenthesis.
The reason this may be needed is that some implementations define YES and NO as follows in objc.h:
#define YES (BOOL)1 #define NO (BOOL)0
where the following is needed for use within the NSNumber literal:
#define YES ((BOOL)1) #define NO ((BOOL)0)
Next week I will show how to use NSDictionary literals.