objective c - Fail to decode Int with NSCoder in Swift -
i using xcode8 beta swift 3.0. tried encode simple object base on nsobject, cannot decode int or nsinteger type. (the encoding process ok)
codes
class model : nsobject, nscoding { var seq: nsnumber? var seq2: int? // problem seq2, nsinteger not ok, either var id: string? var value: string? override init() { super.init() } required init?(coder adecoder: nscoder){ self.seq = adecoder.decodeobject(forkey: "seq") as? nsnumber self.seq2 = adecoder.decodeinteger(forkey: "seq2") self.id = adecoder.decodeobject(forkey: "id") as? string self.value = adecoder.decodeobject(forkey: "value") as? string } func encode(with acoder: nscoder){ acoder.encode(seq, forkey: "seq") acoder.encode(seq2, forkey: "seq2") acoder.encode(id, forkey: "id") acoder.encode(value, forkey: "value") } }
the problem seq2
not int
, rather int?
optional. cannot represented objective-c integer.
you can use decodeobject
:
required init?(coder adecoder: nscoder){ self.seq = adecoder.decodeobject(forkey: "seq") as? nsnumber self.seq2 = adecoder.decodeobject(forkey: "seq2") as? int self.id = adecoder.decodeobject(forkey: "id") as? string self.value = adecoder.decodeobject(forkey: "value") as? string super.init() }
or change not optional:
class model : nsobject, nscoding { var seq: nsnumber? var seq2: int var id: string? var value: string? init(seq: nsnumber, seq2: int, id: string, value: string) { self.seq = seq self.seq2 = seq2 self.id = id self.value = value super.init() } required init?(coder adecoder: nscoder) { self.seq = adecoder.decodeobject(forkey: "seq") as? nsnumber self.seq2 = adecoder.decodeinteger(forkey: "seq2") self.id = adecoder.decodeobject(forkey: "id") as? string self.value = adecoder.decodeobject(forkey: "value") as? string super.init() } func encode(with acoder: nscoder) { acoder.encode(seq, forkey: "seq") acoder.encode(seq2, forkey: "seq2") acoder.encode(id, forkey: "id") acoder.encode(value, forkey: "value") } override var description: string { return "<model; seq=\(seq); seq2=\(seq2); id=\(id); value=\(value)>" } }
Comments
Post a Comment