4

I understand how to use NSCoding to convert my objects to archive objects. That's not my question.

What I'm wondering is why there isn't a default implementation of NSCoding that could handle probably 99% of cases.

For instance, every time I write a custom class that I want to archive, I perform the following:

  1. Implement -(void)encodeWithCoder: and -(id)initWithCoder:.
  2. Go down my property list, writing a pair of statements (one encode, one decode) for each property.
  • If the property is an object, I use the encode/decodeObject method.
  • If the property is a value, I use the corresponding encode/decode method.
  • I always use the property's name as my key.

I would suspect that almost every implementation of NSCoding is exactly like mine, with the only changes being the particular properties that need to be manipulated.

It seems to me that this would be a perfect place for a standard implementation, with the option to override if your particular case if funky.

Do I have a misunderstanding of what's going on? If not, could I add a category on NSObject to implement this common method on all objects in my projects?

mbm29414
  • 11,558
  • 6
  • 56
  • 87

1 Answers1

4

I suspect that the answer to your question is simply that NSCoding was designed long before Objective-C properties existed. (NSCoding was part of the OpenStep spec in 1994, whereas properties arrived with Objective-C 2.0 in 2007.) Additionally, some classes have properties that are not appropriate to be serialized for later.

However, your proposed solution could be a great time-saver! At least one such solution already exists. Check out AutoCoding.

AriX
  • 1,647
  • 2
  • 18
  • 24
  • Regarding "many classes have properties...", I agree. Although I suspect that "many" is practically more like "few". At least, I've rarely excluded any properties from classes I'm archiving when implementing NSCoding. – mbm29414 May 17 '14 at 15:27
  • Could be! If NSCoding and Objective-C 2.0 had been designed at the same time, perhaps "no-archive" could have been one of the property configuration flags (like nonatomic, assign, etc.)! – AriX May 17 '14 at 15:28
  • Luckily AutoCoding provides several easy ways to skip archiving a certain property. – AriX May 17 '14 at 15:29
  • Just looking into it now. Thanks for the link! – mbm29414 May 17 '14 at 15:30