ios - How to query an NSDictionary using an expression written in NSString? -
i want able run following hypothetical function called evaluateexpression:on: , "john" answer.
nsdictionary *dict = @{"result": @[@{@"name": @"john"}, @{@"name": @"mary"}]}; nsstring *expression = @"response['result'][0]['name']"; nsstring *answer = [self evaluateexpression: expression on: dict]; is possible?
there's nsobject category extends valueforkeypath give valueforkeypathwithindexes. lets write this:
nsdictionary *dict = @{@"result": @[@{@"name": @"john"}, @{@"name": @"mary"}]}; nsstring *path = @"result[0].name"; nsstring *answer = [dict valueforkeypathwithindexes:path]; xctassertequalstrings(answer, @"john"); the category psy, here: getting array elements valueforkeypath
@interface nsobject (valueforkeypathwithindexes) -(id)valueforkeypathwithindexes:(nsstring*)fullpath; @end #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; (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 plain old valueforkeypath close, not asked for. may useful in form though:
nsdictionary *dict = @{@"result": @[@{@"name": @"john"}, @{@"name": @"mary"}]}; nsstring *path = @"result.name"; nsstring *answer = [dict valueforkeypath:path]; xctassertequalobjects(answer, (@[@"john", @"mary"]));
Comments
Post a Comment