user3033437 user3033437 - 5 months ago 18
iOS Question

how to reorder an NSMutableDictionary of NSMutableDictionaries

In a loop with json data I'm creating an NSMutableDictionary and inside it I'm storing json parsed values :

for j in json {
var jsonValues = NSMutableDictionary()

//Create main value
guard let value = j.valueForKey("value")?.valueForKey("value")! else{
continue
}

//Get name
guard let Name : String = (value.valueForKey("Name")?.valueForKey("en") as? String) else {
continue
}

jsonValues["name"] = Name

//Get geoposition
guard let geoposition = value.valueForKey("geoposition") else {
return
}

//Get lat
if let lat = geoposition.valueForKey("lat") as? String {

jsonValues["lat"] = lat
let flat : Float = (lat as AnyObject).floatValue


//Get lng
if let lng = geoposition.valueForKey("lng") as? String{

jsonValues["lng"] = lng
let flng : Float = (lng as AnyObject).floatValue

let metters : CLLocationDistance = getDistance(flat, flng: flng)

jsonValues["distance"] = floor(metters)
}
}else{}


nsDict.setValuesForKeysWithDictionary(["\(c)" : jsonValues])
c += 1
}


at the end of the loop I put the jsonValues mutableDictionary inside a global var, another NSMutableDictionary, named nsDict.

I would like to reorder my dictionary of dictionaries, using the
["distance"]
value, which is in metters, so I can show it in a tableView from lower distance to upper. I've been stackoverflowing and googling for a while, but I find only examples with
dictionary.sort()
which is useless for me since I use an NSMutableDictionary. Couldn't find any example with NsMutableDictionary and doesn't really understand the apple docs. In another language, like php, I would had do this with two
do{}while
But I can't manage to do it in swift 2 with the given methods . Anybody can help me?

This is an NSMutableDictionary of NSMutableDictionaries this is why I think the parsing technique is not same as to order one NSMutableDictionary

Answer

NSMutatbleDictionary doesn't retain order (sorted or insertion). You can't sort it.

You need a different approach, such as using an NSArray of sorted keys. See NSDictionary - Sorting Dictionaries.

Comments