2

There is already a similar question regarding decoding, but I wanted to try summarize and see if I got the full picture right.

Basically Apple provides the NSCoder class that allows to encode and decode an object if it is sublcass of the NSCoding class.

Inheriting from that class allows to use the NSCoder encode and decode functions provided by Apple that allow to "serialize" NSDataTypes (and all primitive C structs and data types).

My understanding of the NSCoder class reference is that the encodeObject function is able to detect which object type we pass and hence serialize it in the proper way.

Instaed, when using specif types of int (e.g. int 64) Apple decided to provide a specific function as understanding the "signature" of the data wasn't that trivial (I guess that in low levelel memory an int64 is relatively similar to an int as is a primitive data type and hence there is no NSObject "signature" from which Apple could reverse engineer the data type).

Is my understanding correct? Anyone has a different explanation?

I would also like to ask you some more explanation on the usage of "encodeRootObject" function. There isn't much on the reference and I have seen from some code examples. I understand that archiveRootObject is used to actually save an object, but when shall I use encodeRootObject? Is this used when I try to encode an object of a class that I defined?

Community
  • 1
  • 1
mm24
  • 9,280
  • 12
  • 75
  • 170

1 Answers1

2

Close...

NSCoder is a protocol, not a class, so you don't inherit from it, you implement it. You may inherit from another class which implements the protocol but you always need to implement the encode and decode methods in order to specify how your class contents are to be handled.

encodeObject will store some 'metadata' about the class that is being encoded so that it knowns the type of class that should be recreated during decode.

Wain
  • 118,658
  • 15
  • 128
  • 151