如何在encode函数中修复if / let语句?

时间:2018-06-11 23:53:57

标签: swift nsuserdefaults

class story: NSObject, NSCoding {

    var label = UILabel()
    var title = String()
    var index = Int()
    var cover = UIImage()
    var frame = CGRect()

    func encode(with aCoder: NSCoder) {
        if let label = label { aCoder.encodeObject(label, forKey: "label") as! UILabel }
        if let title = title { aCoder.encodeObject(title, forKey: "title") }
        if let index = index { aCoder.encodeObject(index, forKey: "index") }
        if let cover = cover { aCoder.encodeObject(cover, forKey: "cover") }
        if let frame = frame { aCoder.encodeObject(frame, forKey: "frame") }
    }

    required convenience init?(coder aDecoder: NSCoder) {
        self.init()
        self.label = aDecoder.decodeObject(forKey: "label") as! UILabel
        self.title = aDecoder.decodeObject(forKey: "title") as! String
        self.index = aDecoder.decodeObject(forKey: "index") as! Int
        self.cover = aDecoder.decodeObject(forKey: "cover") as! UIImage
        self.frame = aDecoder.decodeObject(forKey: "frane") as! CGRect
    }

    func formatStorySize() {
        let newWidth = self.frame.width * 0.8
        let newHeight = self.frame.height * 0.9
        let newX = self.frame.origin.x + newWidth / 2
        let newY = self.frame.origin.y + newHeight / 2

        self.frame = CGRect(x: newX, y: newY, width: newWidth, height: newHeight)
    }

    func addLabel(text: String) -> UILabel {
        let label = UILabel()
        label.backgroundColor = UIColor.white
        label.text = text
        label.textAlignment = .center
        let width = self.frame.width
        let height: CGFloat = 40
        let xPos = self.frame.origin.x
        let yPos = self.frame.origin.y + self.frame.height - height
        label.frame = CGRect(x: xPos, y: yPos, width: width, height: height)
        self.title = label.text!
        return(label)
    }
}

有人告诉我,为了将一组自定义类实例保存到UserDefaults,我必须添加编码功能以及解码功能。但是,我收到了错误:

  

条件绑定的初始化程序必须具有可选类型,而不是'UILabel'

在编码函数中的第一行之后,并且在所有连续行之后出现类似的错误。我需要改变什么?

2 个答案:

答案 0 :(得分:0)

这些属性都不是可选的,因此您的if let方法根本不需要encode

func encode(with aCoder: NSCoder) {
    aCoder.encode(label, forKey: "label")
    aCoder.encode(title, forKey: "title")
    aCoder.encode(index, forKey: "index")
    aCoder.encode(cover, forKey: "cover")
    aCoder.encode(frame, forKey: "frame")
}

解决了这个问题后,您不应该使用UserDefaults来保存数据。将编码数据写入文件。

答案 1 :(得分:0)

当您使用条件绑定时,例如if let this = thatthat必须是可选的。

使用var label:UILabel?代替var label = UILabel()