Created
October 9, 2012 17:38
-
-
Save jsumners/3860243 to your computer and use it in GitHub Desktop.
A category for retrieving objects from nested NSDictionaries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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