So, I move on to this guide, and finally I figured out how to archive an object using NSCoding and also initialize it again from the file system using an initializer with an error.
// To encode the object in the first place func encode(with aCoder: NSCoder) { aCoder.encode(name, forKey: "name") } // To 're-initialize' the object required init?(coder aDecoder: NSCoder) { self.name = aDecoder.decodeObject(forKey: "name") as! String super.init() }
However, I'm still a little unsure how the whole process works at a high level. Please tell me where my opinion is wrong.
1) If your object accepts the NSCoding protocol, you can use the encode function (c :) to make the NSCoder object pass through this function and execute the "encode" method, passing the property of the object instance (which the object itself) as the first argument and a string representing the key as the second value.
2) This is a recursive process, so essentially the reason why the property of the object instance (i.e. name) is passed is that the THAT property (which is the object) can be sent with an encoded message and so on and so forth then down down the line until he no longer reaches the NSCoding adopter.
3) The aDecoder object can also decode objects, so when initializing your custom object, you will want to use an initializer with the ability to initialize to decode any object that was set for the ambiguous string key used.
Here is what I really don't understand ...
How does an aDecoder object know which single object to use for a key set? For example, let's say I have 10 instances of objects for dogs. When the system passes aDecoder through, and I use the decodeObject method on it, and it sets self.name to the value of this decoded object by key, how aDecoder knows that this dog name was saved as "Jack", and not capture one of the other names Dog instances by accident, such as "Jodi"?
In other words, as soon as you encode the properties of the object, as the file system knows, so that the properties of the object of instance A are separated from the properties of the object of instance B, so that when the application loads back and the object A is initialized, it only captures the properties of object A ?
thanks