NSDictionary Literals In Objective-C

I’ve previously written about NSNumber and NSArray literals, let’s have a look at NSDictionary literals.

Before we get started, a quick note, 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.

As with NSString objects, which allow definition using literal syntax:

you can now create NSDictionary objects using literals. A range of examples follow, showing the old style definition as well as the new literal syntax:

Notice on line 10 the definition is now the key, followed by a colon, followed by the value – a much more intuitive way to define key-value pairs.

Beyond the obvious shorthand notation of literals, with the old format when defining multiple entries, it was required to end the definition with a nil (see line 18), no more with the literal syntax.

Expanding literals to include arrays, dictionaries and number objects, is a wonderful addition to Objective-C. Thanks Apple.

  1. Pretty cool. I look forward to writing

    NSDictionary *dict = @{
    @”FavoriteOS” : @”Dick’s Operating System”,
    @”FavoriteDrink” : @”Miks Klim”
    };

    • And don’t forget:

      NSDictionary *dict = @{
      @”FavoriteStore” : @”Bob’s Pretty Good Computer Store”,
      @”RecentAction” : @”Krap the rac”
      };

  2. Can I replace objectAtKey with some literals?
    New way could short also reading instructions…

  3. can we use literal syntax to create dynamically allocated objects? If yes can you write the syntax?

Comments are closed.