mazeltov7のweb断片

備忘録的なテキトーなことを書きます。(技術記事はQiitaに移行しました http://qiita.com/mazeltov7 )

NSCodingでIntをdecodeする際にdecodeObjectじゃなくてdecodeIntegerを使う

    // MARK: Properties
    var hoge: String
    var piyo: Int
    
    // MARK: Types
    struct PropertyKey {
        static let hogeKey = "hoge"
        static let piyoKey = "piyo"
    }
    
    // MARK: Initialization
    init?(hoge: String, piyo: Int) {
        self.hoge = hoge
        self.piyo = piyo
        
        super.init()
        
        if hoge.isEmpty || piyo < 0 {
            return nil
        }
    }
    
    // MARK: NSCoding
    func encode(with aCoder: NSCoder) {
        aCoder.encode(hoge, forKey: PropertyKey.hogeKey)
        aCoder.encode(piyo, forKey: PropertyKey.piyoKey)
    }
    
    required convenience init?(coder aDecoder: NSCoder) {
        let hoge = aDecoder.decodeObject(forKey: PropertyKey.hogeKey) as! String
        let piyo = aDecoder.decodeObject(forKey: PropertyKey.piyoKey) as! Int
        
        self.init(hoge: hoge, piyo: piyo)
    }

とか書いてたら、Intのdecodeのところでthread 1 exc_bad_instruction(code=exc_i386_invop subcode=0x0)が出て落ちた。なにやらnilが返ってきてたぽくて、上記エラーになったみたい?
as! Intas? Int ?? 0とかすると0が返ってきてしまう。入れるところまでは値あるので、なんでかなと思っていじってたら、decodeObjectdecodeIntegerに変えたら正しい値が返ってきた。Intの扱いで普通にdecodeObjectでもできた部分もあったのでなんでだろ。備忘録。