Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ValueForKeyPath() returning something unexpected

I am parsing this json:

{
"destination_addresses" : [ "Göteborg, Sverige" ],
"origin_addresses" : [ "Stockholm, Sverige" ],
"rows" : [
   {
      "elements" : [
         {
            "distance" : {
               "text" : "467 km",
               "value" : 466568
            },
            "duration" : {
               "text" : "4 timmar 34 min",
               "value" : 16468
            },
            "status" : "OK"
         }
      ]
   }
],
"status" : "OK"
}

Into an NSDictionary like this:

let dataDict = NSJSONSerialization.JSONObjectWithData(data.dataUsingEncoding(NSUTF8StringEncoding), options: nil, error: nil) as NSDictionary

let distance = dataDict.valueForKeyPath("rows.elements.distance.value")

Now, this works, no crashes or errors. But, I expect it to return 466568 but instead it returns this:

(
        (
        466568
    )
)

I dont know why and I cant use it and cant cast it into anything :(

There is another question similar to this, but the answer there didnt help me because Im not the one to change the json, Google is. So please no hate.

like image 557
Arbitur Avatar asked Oct 31 '22 19:10

Arbitur


1 Answers

valueForKeyPath is returning a nested NSArray. You might want to cast it twice:

let distanceValue = ((distance as NSArray).objectAtIndex(0) as NSArray).objectAtIndex(0) as NSNumber
// or
let distanceValue = (distance as [NSArray])[0][0] as NSNumber

The distance value can't be directly accessed because valueForKeyPath does't implement a selector for array items.

Without valueForKeyPath:

let rows = dataDict.objectForKey("rows") as [NSDictionary]
let elements = rows[0]["elements"] as [NSDictionary]
let distance = elements[0]["distance"] as NSDictionary
let value = distance["value"] as NSNumber
like image 91
pNre Avatar answered Nov 15 '22 06:11

pNre