Search code examples
cocoa-touchcocoansdictionaryplistarchive

Using NSKeyedUnarchiver to read in a file created with writeToFile:atomically:


Is there a difference between these methods when reading an NSDictionary from a file which was written by writeToFile:atomically:?

[someDict writeToFile:filePath atomically:YES];

Reading by:

NSDictionary *dict = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];

vs

NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:filePath];

Solution

  • Yes: the first option won't work at all.

    NSKeyedArchiver and writeToFile: don't use the same format. The writeToFile:atomically: description says:

    Writes a property list representation of the contents of the dictionary to a given path.

    Whereas a keyed archive is

    an architecture-independent stream of bytes that preserves the identity of and the relationships between the objects and values.

    It's more flexible in that it can encode any object that conforms to NSCoding, as opposed to just property list objects.

    Files created using one procedure can't be read with the other.