Last Updated: February 25, 2016
· jordanbondo

Quick NSDictionary with Keys that match the object names

With LLVM 4.0, Collection Literals were introduced, allowing us to create an NSDictionary using literal syntax:

NSDictionary* dict = @{@"key1" : obj1, @"key2" : obj2};

If you're OK with having the keys match the name of the object:

NSDictionary* dict = @{@"stringA" : stringA, @"object2" : object2};

then there is an even faster way to create an NSDictionary: the NSDictionaryOfVariableBindings macro.

NSDictionary* dict = NSDictionaryOfVariableBindings(stringA, object2);

Now just access your objects using the variable names as the keys:

NSString* str = [dict objectForKey:@"stringA"];

The NSDictionaryOfVariableBindings is a macro defined in NSLayoutConstraints.h and is generally used in the process of programmatically creating AutoLayout constraints, BUT, that doesn't mean you can't benefit from using it in other scenarios.

Check out the CLANG 3.5 documentation for info on Literals syntax: http://clang.llvm.org/docs/ObjectiveCLiterals.html

and the "Creating Constraints Programmatically" section of the "Auto Layout Guide" from the Apple Developer documentation for more on creating auto layout constraints programmatically:

5 Responses
Add your response


NSDictionary * dict = @{@"stringA": stringA, @"object2": object2};

This is the correct way to make a NSDictionary

over 1 year ago ·

@jonasman Did you even read this? That's the FIRST THING I said. I also explained what NSDictionaryOfVariableBindings is supposed to be used for.

over 1 year ago ·

Yeap! Ofc i read. But your first and second examles are wrong....

over 1 year ago ·

Cool now they are fixed :D

over 1 year ago ·

Yeah, after I figured out that you were just correcting the syntax error in my example I fixed it, but your original comment sounded like you were criticizing the whole post. Thanks for pointing that out.

over 1 year ago ·