Ruben Kazumov
Ruben Kazumov

Reputation: 3892

NSCoding fails during optional property assignment

Consider following example class:

class C: NSObject, NSCoding {

    var b: Bool? // optional parameter

    // designated initializer
    init (b: Bool){...}

    // initializer by NSCoding protocol
    required init?(coder aDecoder: NSCoder) {
        // Lets assume the Bool parameter 'b' comes as NSObject. 
        // We should: (a) cast it to the type Bool and, 
        // (b) unwrap the value because parameter is optional 
        let _b: Bool = (aDecoder.decodeObject(forKey: keys.bool) as? Bool)! // SUCCESS

        // But by the reference manual, for the parameter of a Bool type
        // we should apply a decodeBool() method of a NSCoder class
        let _a: Bool = aDecoder.decodeBool(forKey: keys.amount) //RUNTIME ERROR
        // We've got 'Tread 1: signal SIGABRT' error 
        // at the NSKeyedUnarchiver.unarchiveObject(...) call

        // Lets try unwrap the value because the parameter 'b' is optional
        let _b: Bool = (aDecoder.decodeBool(forKey: keys.bool))! //ERROR
        // We've got compilation error 'Cannot force unwrap value 
        // non-optional type 'Bool'

        self.b = _b
        super.init()
    }

    // initializer by NSObject protocol
    override convenience init () {...}
    // method by NSCoding protocol
    func encode(with aCoder: NSCoder) {...}  
}

The question is:

Does it mean I have to consider Boolean, Integer, Float etc. types as a generic Object type in case of optional parameters because of the methods like decodeBool(), decodeInteger(), decodeFloat() etc. impossible to unwrap?

Upvotes: 0

Views: 133

Answers (0)

Related Questions