Skip to content

Instantly share code, notes, and snippets.

@starhoshi
Created June 29, 2017 05:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save starhoshi/b53b46d2ea97dafe5dd613f8fd2e36f3 to your computer and use it in GitHub Desktop.
Save starhoshi/b53b46d2ea97dafe5dd613f8fd2e36f3 to your computer and use it in GitHub Desktop.
UserDefault などに class を保存するサンプル
import Foundation
import ObjectMapper
public class User: NSObject, Mappable, NSCoding {
public var id: Int!
public var name: String!
public required init?(map: Map) {
}
public func mapping(map: Map) {
id <- map["id"]
name <- map["name"]
}
required public init(coder: NSCoder) {
id = coder.decodeObject(forKey: "id") as! Int
name = coder.decodeObject(forKey: "name") as! String
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(id, forKey: "id")
aCoder.encode(name, forKey: "name")
}
}
let user = User()
user.id = 0
user.name = "name"
let data = NSKeyedArchiver.archivedData(withRootObject: user)
let unarchivedUser = NSKeyedUnarchiver.unarchiveObject(with: data) as! User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment