سؤال

I have a UITableView that should display some data (Countries for example), clicking one of them should load new UITableView which will display another data relevant to the cell I had clicked on (for example cities in the country), clicking the city should display me information about it. So, this everything will of course use UINavigationController, but how must I arrange the data for Countries->Cities?

هل كانت مفيدة؟

المحلول

I think the most proper way to do it is to develop custom classes for your model. Think of it this way: is a country really just a string? In some apps it may be, but in your's it's at least an object that has a name and contains cities.

Is a city just a string? Again, in some representation, maybe it is, or maybe it associates more data, like population or the mayor's name, or whatever. Is the mayor just a name? ... and so on.

Once you realize this, your table representation becomes better than an array of strings, and (with due respect to the other answer) better than a dictionary. Instead, your table is backed by an array of Country objects. When one is selected, you can hand the selected country self.countries[indexPath.row] to a new view controller with a table that asks it for it's cities: NSArray *cities = self.country.cities... and so on.

نصائح أخرى

One way you could arrange things is to set your countries to be keys in a NSMutableDictionary. The "value" associated with each key would be a NSArray of cities in each country.

So to get a list of all the countries you have, you could do something like:

NSMutableDictionary *myCountryDictionary;
...
...
// populate the dictionary with city arrays associated with each country
...
...

// and then to get a list of all the countries you have in your dictionary:
NSArray *allCountries = [myCountryDictionary allKeys];

Then, when you put a new table onto the navigation controller, you can display the array associated with the country (which is a key in that dictionary).

Makes sense so far?

NSDictionary *citiesByCountry = @{
                                  @"United States" : @[ @"New York", @"Atlanta", @"San Francisco" ],
                                  @"Russia" : @[ @"Moscow", @"Saint Petersberg", @"Novosibirsk" ],
                                  @"North Pole" : @[],
                                  };
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top