Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading NSDictionary from Plist as Listed

I'm using plist to store key-value lists. When the application needs that list, trying load list to a NSDictionary. Everything is well until here.

Here how I load the plist file:

NSString *myPlistFilePath = [[NSBundle mainBundle] pathForResource: @"cities" ofType: @"plist"];
cities = [NSDictionary dictionaryWithContentsOfFile: myPlistFilePath];

When we look at, cities is a NSDictionary. Then I pushed all list key values to a TableView, somehow its not listed as in plist file. Sorting random.

Is there way to figure out? Thanks in advance.

like image 807
Newbie iOS Developer Avatar asked Jan 16 '13 11:01

Newbie iOS Developer


1 Answers

An NSDictionary is not an ordered collection, that is, it does not guarantee to preserve order of the contents in any way. Its only function is to map from keys to values.

If you need the contents ordered, you can extract it from the NSDictionary using for example keysSortedByValueUsingSelector, which will extract the data in the collection, sort it by your criteria and store it in an (order preserving) NSArray.

Alternatively, consider using an Array in the root of the plist, containing an ordered list of city dictionaries. Then if you iterate over the array contained therein, they will be in the array order contained in the plist.

like image 56
Joachim Isaksson Avatar answered Oct 05 '22 22:10

Joachim Isaksson