If I have a large NSDirectory typically from a parsed JSON-object I can access this object with code like so:
[[[[[obj objectForKey:@"root"] objectForKey:@"key1"] objectAtIndex:idx] objectForKey:@"key2"] objectAtIndex:idz];
The line might be a lot longer than this.
Can I optimize this code in any way? At least make it easier to read?
This line will also generate a runtime-error if the object does not correspond, what is the most efficient way to avoid that?
If you were using
-objectForKey:for everything you could use-valueForKeyPath:, as inHowever, this doesn’t work when you need to use
-objectAtIndex:. I don’t think there’s any good solution for you.-valueForKeyPath:also wouldn’t solve the problem of the runtime errors.If you truly want a simple way to do this you could write your own version of
-valueForKeyPath:(call it something else) that provides a syntax for specifying an-objectAtIndex:instead of a key, and that does the appropriate dynamic checks to ensure the object actually responds to the method in question.