darksky
darksky

Reputation: 21049

Table View with Countries / States / Cities

I am downloading some information from a JSON feed about countries, states and their cities. The way I have my final data structure is as follows:

An NSArray where each element holds an NSDictionary. Each NSDictionary has a key of the name of the country, and a value of an NSDictionary corresponding to the states. Each of those NSDictionarys hold a key of the name of the state and a value of an array with a list of the names of the cities.

I want to display each country in a different section in a table view. To return the number of countries (aka. numbeber of sections), I can just do [countriesArray count].

However, to return the number of states and cities of each country, that seems impossible with my current structure. I can access [countriesArray objectAtIndex:index], but after that, how can I access the value of that dictionary (the key is the name of the country)?

Should I restructure my data structures? If so, what's the best way to sort this kind of data?

Upvotes: 0

Views: 394

Answers (3)

Rahul Wakade
Rahul Wakade

Reputation: 4805

NSArray *countryKeys = [countriesArray allKeys]; //will return you an array of all keys(country names).

Also, instead of doing [countriesArray objectAtIndex:index], you should do [countriesArray valueForKey:[countryKeys objectAtIndex:index]];

Upvotes: 0

Apurv
Apurv

Reputation: 17186

You can have below data structure which may help.

A container NSArray which has NSDictionary as its object. Each dictionary has fixed keys like: countryName and stateInfo. The value of this keys will be: string and NSDictionary.

Each stateInfo dictionary should have fixed keys like: stateName, cities the value of this keys will be: string and NSarray of cities.

Upvotes: 0

Senthilkumar
Senthilkumar

Reputation: 2481

you may handle this problem using the collapsible tableview

from this you can display the relevant data as your requirement.

Upvotes: 1

Related Questions