简体   繁体   中英

How to initialize a custom class instance that conforms to NSCoding?

I'm trying to use NSKeyedArchiver to store custom class instance.

class feedBack: NSObject, NSCoding {

var choiceA = 0
var choiceB = 0
var choiceC = 0
var choiceD = 0
var choiceNULL = 0
var sheetName = ""

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(self.choiceA, forKey: "choiceA")
    aCoder.encodeObject(self.choiceB, forKey: "choiceB")
    aCoder.encodeObject(self.choiceC, forKey: "choiceC")
    aCoder.encodeObject(self.choiceD, forKey: "choiceD")
    aCoder.encodeObject(self.choiceNULL, forKey: "choiceNULL")
    aCoder.encodeObject(self.sheetName, forKey: "sheetName")
}

required init(coder aDecoder: NSCoder) {
    self.choiceA = aDecoder.decodeObjectForKey("choiceA") as! Int
    self.choiceB = aDecoder.decodeObjectForKey("choiceB") as! Int
    self.choiceC = aDecoder.decodeObjectForKey("choiceC") as! Int
    self.choiceD = aDecoder.decodeObjectForKey("choiceD") as! Int
    self.choiceNULL = aDecoder.decodeObjectForKey("choiceNULL") as! Int
    self.sheetName = aDecoder.decodeObjectForKey("sheetName") as! String


}


}

Before feedBack conforms to NSCoding, I use var fb = feedBack() to create a new instance of feedBack. Now the compiler throws Missing argument for parameter coder in call error.

Since the initWithCoder is required, how do I call the previous initializer with no parameter?

Just override init() and that should do it.

class feedBack: NSObject, NSCoding {

    var choiceA = 0
    var choiceB = 0
    var choiceC = 0
    var choiceD = 0
    var choiceNULL = 0
    var sheetName = ""

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.choiceA, forKey: "choiceA")
        aCoder.encodeObject(self.choiceB, forKey: "choiceB")
        aCoder.encodeObject(self.choiceC, forKey: "choiceC")
        aCoder.encodeObject(self.choiceD, forKey: "choiceD")
        aCoder.encodeObject(self.choiceNULL, forKey: "choiceNULL")
        aCoder.encodeObject(self.sheetName, forKey: "sheetName")
    }

    required init(coder aDecoder: NSCoder) {
        self.choiceA = aDecoder.decodeObjectForKey("choiceA") as! Int
        self.choiceB = aDecoder.decodeObjectForKey("choiceB") as! Int
        self.choiceC = aDecoder.decodeObjectForKey("choiceC") as! Int
        self.choiceD = aDecoder.decodeObjectForKey("choiceD") as! Int
        self.choiceNULL = aDecoder.decodeObjectForKey("choiceNULL") as! Int
        self.sheetName = aDecoder.decodeObjectForKey("sheetName") as! String
    }

    override init(){

    }

}
feedBack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM