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! Int
をas? Int ?? 0
とかすると0が返ってきてしまう。入れるところまでは値あるので、なんでかなと思っていじってたら、decodeObject
をdecodeInteger
に変えたら正しい値が返ってきた。Intの扱いで普通にdecodeObject
でもできた部分もあったのでなんでだろ。備忘録。