2

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 ?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Milianoo
  • 1,476
  • 1
  • 10
  • 9

1 Answers1

10

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.

Wevah
  • 28,182
  • 7
  • 83
  • 72