views:

288

answers:

2

Is there any way to access an NSArray element with valueForKeyPath? Google's reverse geocoder service, for example, returns a very complex data structure. If I want to get the city, right now I have to break it into two calls, like this:

NSDictionary *address = [NSString stringWithString:[[[dictionary objectForKey:@"Placemark"] objectAtIndex:0] objectForKey:@"address"]];
NSLog(@"%@", [address valueForKeyPath:@"AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName"]);

Just wondering if there's a way to shoehorn the objectAtIndex: call into the valueForKeyPath string. I tried a javascript-esque formulation like @"Placemark[0].address" but no dice.

+4  A: 

Unfortunately, no. The full documentation for what's allowed using Key-Value Coding is here. There are not, to my knowledge, any operators that allow you to grab a particular array or set object.

Alex
A: 

I don't think this is possible.

This looks quite scary and shouldn't work.

NSDictionary *address = [NSString stringWithString: ...];

You could improve by using the new dot-syntax provided by the objective-c 2.0 runtime:

NSDictionary *address = [[dictionary.Placemark objectAtIndex:0] objectForKey:@"address"];
NSLog(@"%@", address.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName);
Georg
It should “work” as long as he only treats `address` as an NSString, but the compiler should give a warning and the code stop working if he ever treats it as the NSDictionary that he told the compiler it is. You're correct that this is a problem.
Peter Hosey
He doesn't as can be seen in the example.
Georg
Ooops, yeah, that stringWithString: thing was left over from some tests I was doing. I'm not using it in real code, don't worry!
jsd