2

I discovered today that there is a much less tedious way to create arrays and dictionaries on the fly:

NSArray *myArray = @[@"one", @"two", @"three"];

NSDictionary *myDict = @{@"key": @"value", @"key2": @"value2"};

Is this a rather new addition to the objective-c language and what is the name of these constructs?

Besi
  • 22,579
  • 24
  • 131
  • 223

3 Answers3

4

New as of Xcode 4.4. I've heard them referred to as collection literals.

EDIT to add:

You can also reference members of NSArray and NSDictionary as array[1] and dictionary[@"key"]. The creation syntax is backwards compatible as it is fully expanded at build. The accessor syntax is not as it involves changes to the runtime.

marramgrass
  • 1,411
  • 11
  • 17
  • You can only do the referencing at this time on Lion and iOS 5 by extending the capabilities of the runtime, see http://stackoverflow.com/a/11694878/96716 – David H Aug 03 '12 at 23:56
2

They are part of Apple's LLVM 4.0 compiler, which shipped in XCode 4.4.

More information can be found here on LLVM's website, under the "Grammar Additions" section. Other new literal syntax exist as well, which is also documented on the website.

vcsjones
  • 138,677
  • 31
  • 291
  • 286
2

Ye.. there are some other examples:

// character literals.
  NSNumber *theLetterZ = @'Z';          // equivalent to [NSNumber numberWithChar:'Z']

  // integral literals.
  NSNumber *fortyTwo = @42;             // equivalent to [NSNumber numberWithInt:42]
  NSNumber *fortyTwoUnsigned = @42U;    // equivalent to [NSNumber numberWithUnsignedInt:42U]
  NSNumber *fortyTwoLong = @42L;        // equivalent to [NSNumber numberWithLong:42L]
  NSNumber *fortyTwoLongLong = @42LL;   // equivalent to [NSNumber numberWithLongLong:42LL]

  // floating point literals.
  NSNumber *piFloat = @3.141592654F;    // equivalent to [NSNumber numberWithFloat:3.141592654F]
  NSNumber *piDouble = @3.1415926535;   // equivalent to [NSNumber numberWithDouble:3.1415926535]

  // BOOL literals.
  NSNumber *yesNumber = @YES;           // equivalent to [NSNumber numberWithBool:YES]
  NSNumber *noNumber = @NO;             // equivalent to [NSNumber numberWithBool:NO]

I first saw it on java! Kinda cool :)

vcsjones
  • 138,677
  • 31
  • 291
  • 286
NSPunk
  • 502
  • 4
  • 14