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.
We can create our own class to use the dot syntax to access a dictionary's keys.
An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.
There is no dot syntax for NSDictionary
, but should consider using objectForKey:
instead of valueForKey:
Difference between objectForKey and valueForKey?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With