I guess I just don't know what the difference is because I don't understand the "black box" but what is the difference between using either one of these methods?
When should I be using
NSData
writeToFile: atomically:
and when should I be using
[NSKeyedArchiver archiveRootObject: toFile:]
And what are the pros and cons to using each?
These two APIs do different things:
NSData
writes out "raw" bytes to the file. You can restore the structure behind these bytes by assuming that the bytes that you read back are in the right places. In a sense, this is similar to applying a cookie cutter to a piece that has some structure, expecting the right pieces to appear in the right spots. A direct consequence of this approach is that the data does not survive changes of code - if the structure into which you read your data did change, saved data from before the change will cause errors.NSKeyedArchiver
preserves the structure of the object along with its data. This results in a slightly larger archives, yet the structure becomes more robust, in terms of surviving changes to the underlying data.If you need to save a simple piece of unstructured data, you could use either one. If the data that you are saving has structure, prefer NSKeyedArchiver
, especially if you would like to preserve some flexibility in the future.