Swift NSCoding Not working

前端 未结 4 1731
小蘑菇
小蘑菇 2020-12-23 21:53

I\'m having trouble using NSCoding in Swift. I have attempted to implement the protocol but I get a crash whenever I call my save() method. Xcode p

4条回答
  •  被撕碎了的回忆
    2020-12-23 22:43

    The following code does not work

    class Hero : AnyObject, NSCoding {
    
        var heroID: String?
        var title: String?
        var imageName: String?
        var detail: String?
        var star: String?
    
        init() {
    
        }
    
    
        func update(_ dictionary: Dictionary) {
    
            heroID = dictionary["imageName"] as? String
            title = dictionary["title"] as? String
            imageName = dictionary["imageName"] as? String
            detail = dictionary["detail"] as? String
            star = dictionary["star"] as? String
    
        }
        required init?(coder aDecoder: NSCoder) {
            heroID = aDecoder.decodeObject(forKey: "heroID") as? String
            title = aDecoder.decodeObject(forKey: "title") as? String
            imageName = aDecoder.decodeObject(forKey: "imageName") as? String
            detail = aDecoder.decodeObject(forKey: "detail") as? String
            star = aDecoder.decodeObject(forKey: "star") as? String
        }
    
        func encode(with aCoder: NSCoder) {
            aCoder.encode(heroID, forKey: "heroID")
            aCoder.encode(title, forKey: "title")
            aCoder.encode(imageName, forKey: "imageName")
            aCoder.encode(detail, forKey: "detail")
            aCoder.encode(star, forKey: "star")
        }
    }
    

    Be sure to write like this

    class Hero : NSObject, NSCoding {
    
        var heroID: String?
        var title: String?
        var imageName: String?
        var detail: String?
        var star: String?
    
        override init() {
    
        }
    }
    

提交回复
热议问题