5

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.

0

3 Answers 3

4

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.

1
1

NSDictionary is not an ordered data structure.

Objects are listed based on allKeys functions and keys are listed in undefined way.

See the apple doc for allKeys function.

allKeys Returns a new array containing the dictionary’s keys.

  • (NSArray *)allKeys

Return Value A new array containing the dictionary’s keys, or an empty array if the dictionary has no entries.

Discussion The order of the elements in the array is not defined.

1
  • 2
    Thanks for answer, so what's your suggestion to load as listed? Jan 16, 2013 at 11:27
0

If you wish to avoid using a selector to sort the keys, consider using an Array in the root of the plist. Then when you iterate over the array, the order is preserved. This runs o(n), which is shorter than the fastest possible sort algorithm by a factor of log(n)
eg:

cities{
  list[
    city{}
    city{}
    city{}
    ...
  ]
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.