【问题标题】:How to initialize a custom class instance that conforms to NSCoding?如何初始化一个符合 NSCoding 的自定义类实例?
【发布时间】:2015-07-06 11:59:45
【问题描述】:

我正在尝试使用 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是必填项,那如何不带参数调用之前的初始化器呢?

【问题讨论】:

    标签: ios swift class initialization


    【解决方案1】:

    只需覆盖 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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多