Search code examples
iosswiftdictionarycocoa-touchplist

Using Dates as keys in a dictionary saved to a plist


I have a dictionary which I save to and read from a plist file.

When the dictionary type is [String : String], I can add entries and save it to the plist with no problems.

If I change its type to [Date : String], I can add entries, and I can save it to the plist, but when I try to read it, it's empty.

I'm not modifying any code, except the type in the variable declaration and in the two functions to read and write to the plist.

What am I missing?


Solution

  • In property lists all keys are required to be strings.

    From the documentation:

    And although NSDictionary and CFDictionary objects allow their keys to be objects of any type, if the keys are not string objects, the collections are not property-list objects.

    If you are using PropertyListSerialization rather than the convenience read and write methods of NSDictionary and NSArray you will certainly get an error.