Last active
August 29, 2015 13:57
-
-
Save karnlund/9774907 to your computer and use it in GitHub Desktop.
Extension of NSObject that allows array indexes to be used in KVO key path strings (NSString* personsFriendsName = [obj valueForKeyPathsWithIndexes:@"me.friends[0].name"])
This file contains hidden or 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 "NSObject+ValueForKeyPathWithIndexes.h" | |
@implementation NSObject (ValueForKeyPathWithIndexes) | |
-(id)valueForKeyPathWithIndexes:(NSString*)fullPath | |
{ | |
NSRange testrange = [fullPath rangeOfString:@"["]; | |
if (testrange.location == NSNotFound) | |
return [self valueForKeyPath:fullPath]; | |
NSArray* parts = [fullPath componentsSeparatedByString:@"."]; | |
id currentObj = self; | |
for (NSString* part in parts) | |
{ | |
NSRange range1 = [part rangeOfString:@"["]; | |
if (range1.location == NSNotFound) | |
{ | |
currentObj = [currentObj valueForKey:part]; | |
} | |
else | |
{ | |
NSString* arrayKey = [part substringToIndex:range1.location]; | |
int index = [[[part substringToIndex:part.length-1] substringFromIndex:range1.location+1] intValue]; | |
currentObj = [[currentObj valueForKey:arrayKey] objectAtIndex:index]; | |
} | |
} | |
return currentObj; | |
} | |
@end |
This file contains hidden or 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
@interface NSObject (ValueForKeyPathWithIndexes) | |
-(id)valueForKeyPathWithIndexes:(NSString*)fullPath; | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment