Swift:尝试实现NSCoding

时间:2015-11-21 19:20:54

标签: swift uiimage nscoding

我试图将NSCoding协议添加到我的自定义类:

class Convo: NSObject, NSCoding {
    var name: String
    var pic: UIImage

    override init() {
        self.name = "Dror"
        self.pic = UIImage (named: "NoPic.png")!
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObjectForKey("name") as! String
        self.pic = aDecoder.decodeObjectForKey("pic") as! UIImage
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
        aCoder.encodeObject(self.pic, forKey: "pic")
    }

}

但它在行上弹出错误:

self.pic = aDecoder.decodeObjectForKey("pic") as! UIImage

控制台中的错误是:

  

致命错误:在解包可选值时意外发现nil

xcode中的错误是:

  

主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

我不知道该怎么做。

编辑: 运行此代码时:

class Convo: NSObject, NSCoding {
    var name: String
    var pic: UIImage!

    override init() {
        self.name = "Dror"
        self.pic = UIImage (named: "NoPic.png")!
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObjectForKey("name") as! String
        self.pic = aDecoder.decodeObjectForKey("pic") as? UIImage
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
        aCoder.encodeObject(self.pic, forKey: "pic")
    }
}

它编译好了,但是self.pic到底是nil而不是UIImage(命名为:“NoPic.png”)

2 个答案:

答案 0 :(得分:1)

您确定资产中需要图片吗? “NoPic.png”

好的,这是一些变化:

class Convo: NSObject, NSCoding {
    var name: String
    var pic: UIImage?

    override init() {
        self.name = "Dror"
        self.pic = UIImage (named: "NoPic")
        super.init()
    }

它适用于我,但您必须确保图像存在于您的资产中。你可以跳过.png格式

答案 1 :(得分:0)

这有效:

class Convo: NSObject, NSCoding {
    var name: String
    var pic: UIImage?

    override init() {
        self.name = "Dror"
        self.pic = UIImage (named: "NoPic.png")
        super.init()
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObjectForKey("name") as! String
        self.pic = aDecoder.decodeObjectForKey("pic") as? UIImage
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.name, forKey: "name")
        aCoder.encodeObject(self.pic, forKey: "pic")
    }
}