How to implement NSCoding in a custom subclass (Swift 3, 4)

تعرفه تبلیغات در سایت
عنوان عکس
عنوان عکس
عنوان عکس
عنوان عکس
عنوان عکس

آرشیو مطالب

جستجوگر

یافته ها در جستجو

    امکانات وب

    برچسب ها

    Vote count: 0

    I'm working on a project (Swift 4) and I want to save an array of custom Objects which are displayed on a table view. To do that, I have to adopt the NSCoding protocol, which in my super class works perfectly. But if I try to adopt the NSCoding protocol to my subclass, I get the error, that the additional property, which is not in the super class, was not initialized.

    Here some example code, which should represent my problem.

    //The first class of Objects I want to save
    
    class Vehicle: NSObject, NSCoding {
       var wheels: Int
       var color: String
    
       init(wheels: Int, color: String) {
          self.wheels = wheels
          self.color = color
       }
    
       required init(coder aDecoder: NSCoder) {
    
        if let wheelsInt = aDecoder.decodeInteger(forKey: "wheels") {
            wheels = wheelsInt
            }
        if let colorObj = aDecoder.decodeObject(forKey:"colour") as? String {
            color = colorObj
            }
    
        }
    
        func encode(with aCoder: NSCoder) {
    
             aCoder.encode(self.wheels, forKey: "wheels")
             aCoder.encode(self.color, forKey: "color")
    
        }
    
    }
    
    
    //The second class of Objects I want to save
    
    class Car: Vehicle {
        var manufacturer: String //that's the additional property
    
        init(wheels: Int, color: String, manufacturer: String) {
             self.manufacturer = manufacturer
             super.init(name: name, verfuegbarkeit: verfuegbarkeit, kursnummer: kursnummer, preis: preis)
        }
    }
    

    I just don't know how to properly adapt the Subclass to the NSCoding protocol in order for it to work.

    When I try to implement the encode function and the required init function, I get the error mentioned above.

    asked 38 secs ago
    Thomas

    نویسنده : استخدام کار بازدید : 0 تاريخ : جمعه 21 مهر 1396 ساعت: 23:07
    برچسب‌ها :