1

I'm having a bit of a struggle with NSKeyedArchiver and NSKeyedUnarchiver when the properties of the object change between the archive and unarchive process. Here's a concrete example:

I have a class, let's say Task, and it has the attributes name and desc, both of type NSString. Now, I archive using NSKeyedArchiver archivedDataWithRootObject and write it to a file. I can later read it from a file and use NSKeyedUnarchiver unarchiveObjectWithData(data) to get right back where I want to be. The problem comes when Task acquires a new property and, to make things interesting, loses one.

So now, Task has name, which is an NSString, but desc is missing. Further, I add the property dateDue of type NSDate. And then fire up the simulator. The problem is that what's unarchived is the old Task with the old desc property but not the new dateDue.

My initFromCoder actually takes the case into account where a property is not present in the current class and doesn't attempt to decode it.

Is there a way to explain to the NSCoder methods not to create me an exact replica of the object as it was when I serialized it (I realized that is part of the definition of serialization/deserialization) but rather to allow me the flexibility to version it?

Thanks

Steve Ross
  • 4,134
  • 1
  • 28
  • 40

1 Answers1

1

There is one simple way - write the version to the data and read it as the beginning of initFromCoder. If the version comparison fails, just return nil from the initializer.

When you add a property, even if you attempt to decode the data, you just get a nil value. You can always check for nil values.

When you remove a property, there shouldn't be any problem.

Note that you are the one implementing both encoding and decoding, so you can implement it any way you want.

Sulthan
  • 128,090
  • 22
  • 218
  • 270