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

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -