Skip to content

Instantly share code, notes, and snippets.

@Otbivnoe
Created December 22, 2016 09:19
Show Gist options
  • Save Otbivnoe/c42b9f1cce86008a4fbf65c818c62682 to your computer and use it in GitHub Desktop.
Save Otbivnoe/c42b9f1cce86008a4fbf65c818c62682 to your computer and use it in GitHub Desktop.
Convenient object coding via ObjectMapper - Example
class Base: NSObject, NSCoding, StaticMappable {
var d: Int?
override init() {}
init(d: Int?) {
self.d = d
}
//MARK: NSCoding
required init?(coder aDecoder: NSCoder) {
guard let json = aDecoder.decodeObject(forKey: "key") as? [String : Any] else {
return nil
}
super.init()
let map = Map(mappingType: .fromJSON, JSON: json)
mapping(map: map)
}
func encode(with aCoder: NSCoder) {
aCoder.encode(toJSON(), forKey: "key")
}
//MARK: StaticMappable
static func objectForMapping(map: ObjectMapper.Map) -> BaseMappable? {
return nil
}
func mapping(map: Map) {
d <- map["d"]
}
}
final class A: Base {
var a: Int!
var b: Int!
init(a: Int, b: Int, d: Int?) {
super.init(d: d)
self.a = a
self.b = b
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func mapping(map: Map) {
super.mapping(map: map)
a <- map["a"]
b <- map["b"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment