Search code examples
objective-cjsonnsstringnsarray

Objective-C String handling issue


I'm trying to read from a JSON response something like below

{ 
"URL": 
  { 
     "target": "www.google.com", 
    "0": [ 92, 15 ], 
    "1": [ 92, 16 ], 
    "2": [ 74, 15 ], 
    "4": [ 5, 16 ] 
  } 
}

Using SBJSON I've managed to get 'target' field,

testString = [[result objectForKey:@"URL"] objectForKey:@"target"];

when I do a NSLOG it shows www.google.com

but this piece of code doesn't work for other key pairs.

testString = [[result objectForKey:@"URL"] objectForKey:@"0"];

and when I try to print testString it gives me an error.

In console I printed values, they were,

(lldb) po testString
(NSString *) $4 = 0x0864b190 <__NSArrayM 0x864b190>(
65,
27
)

How do I extract these 65 and 27 ?


Solution

  • that is an array of objects. try:

    NSArray * array = [[result objectForKey:@"URL"] objectForKey:@"0"];
    id a = [array objectAtIndex:0]; // 65
    id b = [array objectAtIndex:1]; // 27
    
    // now determine the type of objects in the array, and use them appropriately:
    if ([a isKindOfClass:[NSString class]]) {
      NSString * string = a;
      ...use appropriately
    }
    else if ([a isKindOfClass:[NSDecimalNumber class]]) {
      NSDecimalNumber * number = a;
      ...use appropriately
    }
    ...
    else {
      assert(0 && "type not supported");
    }