Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access NSDictionary via dot notation?

Is there a way via dot notation to access the values of keys in an NSDictionary like this?

NSDictionary *returnVal = [NSDictionary dictionaryWithObjectsAndKeys:@"Saturn", @"name", @"Gas Giant", @"type", nil];
NSLog(@"VALUE: %@", [returnVal valueForKey:@"name"]); // This is how I am doing it now.
like image 653
fuzzygoat Avatar asked Feb 13 '12 16:02

fuzzygoat


People also ask

Can I access Python dictionary with dot?

We can create our own class to use the dot syntax to access a dictionary's keys.

What is Nsdictionary?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

There is no dot syntax for NSDictionary, but should consider using objectForKey: instead of valueForKey:

Difference between objectForKey and valueForKey?

like image 134
kevboh Avatar answered Sep 20 '22 06:09

kevboh


Not really, no.

The dot notation is a shorthand way of calling a method with that selector name. In other words, this...

NSLog(@"Hello, %@", foo.bar.name);

...is the same as this...

NSLog(@"Hello, %@", [[foo bar] name]);

When I say "same", I mean they are compiled down to the same code. It's just syntactic sugar.

A plain NSDictionary won't act that way. You could sort of fake it with Key Value Coding, which lets you call valueForKeyPath to get properties like this:

NSLog(@"Hello, %@", [foo valueForKeyPath:@"bar.name"]);

If you really wanted to be able to write foo.bar.name in your code, however, you'd have to make a custom class that overrides forwardInvocation:; this lets you catch an unknown message to an object and do something else with it besides throw an error. In this case, you could change the unknown selector to a lookup on an NSDictionary instance it contains.

But even if you did that, the compiler would probably still generate warnings unless you made header files that declared those property names to exist.

like image 44
benzado Avatar answered Sep 20 '22 06:09

benzado