Search code examples
objective-cnsstringnsdictionarykey-valuekeyvaluepair

Converting NSString to key value pair


I have a response from server which is NSString and looks like this

resp=handshake&clientid=47D3B27C048031D1&success=true&version=1.0

I want to convert it to key value pair , something like dictionary or in an array . I couldn't find any useful built-in function for decoding the NSString to NSdictionary and replacing the & with space didn't solve my problem , can anyone give me any idea or is there any function for this problem ?


Solution

  • This should work (off the top of my head):

    NSMutableDictionary *pairs = [NSMutableDictionary dictionary];
    
    for (NSString *pairString in [str componentsSeparatedByString:@"&"]) {
        NSArray *pair = [pairString componentsSeparatedByString:@"="];
    
        if ([pair count] != 2)
            continue;
    
        [pairs setObject:[pair objectAtIndex:1] forKey:[pair objectAtIndex:0]];
    }
    

    or you could use an NSScanner, though for something as short as a query string the extra couple of arrays won't make a performance difference.