yd9zfg
Last Updated: February 25, 2016
·
2.993K
· 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:
https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AutolayoutPG/AutoLayoutinCode/AutoLayoutinCode.html#//apple_ref/doc/uid/TP40010853-CH11-SW1

5 Responses
Add your response

14325

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

This is the correct way to make a NSDictionary

over 1 year ago ·
14327

@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 ·
14329

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

over 1 year ago ·
14351

Cool now they are fixed :D

over 1 year ago ·
14353

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 ·