Skip to content

Instantly share code, notes, and snippets.

@karnlund
Last active August 29, 2015 13:57
Show Gist options
  • Save karnlund/9774907 to your computer and use it in GitHub Desktop.
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"])
#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
@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