如何初始化符合NSCoding的自定义类实例?

时间:2015-07-06 11:59:46

标签: ios swift class initialization

我正在尝试使用NSKeyedArchiver存储自定义类实例。

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


}


}

feedBack符合NSCoding之前,我使用var fb = feedBack()创建了一个新的feedBack实例。 现在编译器抛出Missing argument for parameter coder in call错误。

由于需要initWithCoder,如何在没有参数的情况下调用前一个初始值设定项?

1 个答案:

答案 0 :(得分:0)

只需覆盖init()即可。

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()