Skip to content

Instantly share code, notes, and snippets.

@jsumners
Created October 9, 2012 17:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jsumners/3860243 to your computer and use it in GitHub Desktop.
Save jsumners/3860243 to your computer and use it in GitHub Desktop.
A category for retrieving objects from nested NSDictionaries
#import <Foundation/Foundation.h>
@interface NSDictionary (JBSObjectForPath)
/**
Returns the object from a nested `NSDictionary` at the given path, with path
components separated by a "/". For example, if you have the following
dictionary:
~~~~
{"foo":{"bar":"foobar"}}
~~~~
Then the path `@"foo/bar"` would return the `NSString` `@"foobar"`.
@param path A string path with compenents separated by a "/".
@return The object at the specified path.
*/
- (id)objectForKeyPath:(NSString *)path;
/**
@see objectForKeyPath:
@param path A string path with components separated by the specified separator.
@param separator A string that defines the components separator.
@return The object at the specified path.
*/
- (id)objectForKeyPath:(NSString *)path withPathSeparator:(NSString *)separator;
@end
#import "NSDictionary+JBSObjectForPath.h"
@implementation NSDictionary (JBSObjectForPath)
- (id)objectForKeyPath:(NSString *)path
{
return [self objectForKeyPath:path withPathSeparator:@"/"];
}
- (id)objectForKeyPath:(NSString *)path withPathSeparator:(NSString *)separator
{
NSCharacterSet *cset = [NSCharacterSet
characterSetWithCharactersInString:separator];
if (!path || [path rangeOfCharacterFromSet:cset].location == NSNotFound) {
return nil;
}
NSArray *keys = [path componentsSeparatedByString:separator];
__block id (^getObject)();
getObject = ^id(NSArray *keypath, NSDictionary *dict) {
if ([keypath count] == 1) {
return [dict objectForKey:[keypath objectAtIndex:0]];
}
NSRange range;
range.location = 1;
range.length = [keypath count] - 1;
NSArray *ar = [keypath subarrayWithRange:range];
return getObject(ar, [dict objectForKey:[keypath objectAtIndex:0]]);
};
return getObject(keys, self);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment