views:

30

answers:

1

I found the following tip for parsing XML in Objective-C on a post on this site. However, y always seems to equal null. I'm wondering if someone can clarify what is going on here.

NSString * q = [myURL query];
NSArray * pairs = [q componentsSeparatedByString:@"&"];
NSMutableDictionary * kvPairs = [NSMutableDictionary dictionary];
for (NSString * pair in pairs) {
  NSArray * bits = [pair componentsSeparatedByString:@"="];
  NSString * key = [[bits objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
  NSString * value = [[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
  [kvPairs setObject:value forKey:key];
}

NSLog(@"y = %@", [kvPairs objectForKey:@"y"]);
A: 

Establish a string made from a URL call something like http://www.somewhere.com/form?name=john&x=123&y=456 NSString * q = [myURL query];

Create an array of key value pairs name=john, x=123, y=456 NSArray * pairs = [q componentsSeparatedByString:@"&"];

initialize a dictionary for storing key-value pairs NSMutableDictionary * kvPairs = [NSMutableDictionary dictionary];

Initialize a temp variable "pair" and iterate through the array for (NSString * pair in pairs) {

Separate the key, left side of = from the value NSArray * bits = [pair componentsSeparatedByString:@"="]; store the key NSString * key = [[bits objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; store the value NSString * value = [[bits objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSASCIIStringEncoding];

fill the dictionary with values for the keys [kvPairs setObject:value forKey:key]; }

Here you will print out the value for the key "y" which should be 456 NSLog(@"y = %@", [kvPairs objectForKey:@"y"]);

Not having the rest of your code, perhaps the url being sent does not have a key name "y" like I've broken down in my example.

I hope this helps!!

Nungster