Soheil Novinfard Soheil Novinfard - 2 months ago 24
Objective-C Question

Sort dictionary of dictionaries in Objective C

I have a dictionary of dictionaries (for countries) as below:

US = {
areaCode = 1;
code = US;
name = "United States";
};
UY = {
areaCode = 598;
code = UY;
name = Uruguay;
};
UZ = {
areaCode = 998;
code = UZ;
name = Uzbekistan;
};


How could I sort it with "name" key of inner dictionary ?

More Explanation and Edit:
I created this dictionary (key/value system) as below:

NSString *countriesPath = [bundle pathForResource:@"countries" ofType:@"csv"];
NSMutableDictionary *countries = [NSMutableDictionary dictionary];
fileContents = [NSString stringWithContentsOfFile:countriesPath usedEncoding:nil error:nil];
rows = [fileContents componentsSeparatedByString:@"\n"];
for (NSString *row in rows){
NSArray* columns = [row componentsSeparatedByString:@","];
NSDictionary *CountryRowData = @{
@"code": columns[0],
@"name": columns[1],
@"areaCode": columns[2]
};
countries[columns[0]]= CountryRowData;
}
_countries = countries;

Answer

You can't sort a dictionary—it's an unordered collection. You can sort an array of keys, though:

NSDictionary *countries;

NSArray *sortedKeys = [[countries allKeys] sortedArrayUsingComparator:^NSComparisonResult(NSString *key1, NSString *key2) {
    return [countries[key1][@"name"] compare:countries[key2][@"name"]];
}];

// sortedKeys is now ( US, UY, UZ )