NSCoding requires init(coder:), but there is also the optional version of this method init?(coder:).
What exactly should one do if this returns nil? Is this even an issue?
Say you are initializing a large hierarchy of objects with init(coder:), with each object's child objects themselves being initialized using init?(coder:). If somewhere along the way one of those objects is nil, wouldn't the app crash? The parent object is not expecting a nil child.
What does it even mean to "init nil"?
class Parent: NSCoding {
var children: [Child]
required init?(coder aDecoder: NSCoder) {
guard let children = aDecoder.decodeObject(forKey: "children") as? [Child] else { return nil }
self.children = children
}
}
class Child: NSCoding {
var name: String
required init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObject(forKey: "name") as? String else { return nil }
self.name = name
}
}
One strategy would be to simply return a new instance rather than simply returning nil. The data would be lost, but it the app would run.
initmethod cannot returnnil. Theguardis not needed either in this case.self.name = aDecoder.decodeObject(forKey: "name") as! String. If you dont want to risk crashing, one way is to initialize with a default valueself.name = aDecoder.decodeObject(forKey: "name") as? String ?? "".