Skip to content

Instantly share code, notes, and snippets.

@andrea-prearo
Created May 2, 2018 13:08
Show Gist options
  • Save andrea-prearo/5d9aa5c59ed80ef454d121825f4e17d0 to your computer and use it in GitHub Desktop.
Save andrea-prearo/5d9aa5c59ed80ef454d121825f4e17d0 to your computer and use it in GitHub Desktop.
class User: NSManagedObject, Codable {
[...]
// MARK: - Core Data Managed Object
@NSManaged var avatarUrl: String?
@NSManaged var username: String?
@NSManaged var role: String?
// MARK: - Decodable
required convenience init(from decoder: Decoder) throws {
guard let codingUserInfoKeyManagedObjectContext = CodingUserInfoKey.managedObjectContext,
let managedObjectContext = decoder.userInfo[codingUserInfoKeyManagedObjectContext] as? NSManagedObjectContext,
let entity = NSEntityDescription.entity(forEntityName: "User", in: managedObjectContext) else {
fatalError("Failed to decode User")
}
self.init(entity: entity, insertInto: managedObjectContext)
let container = try decoder.container(keyedBy: CodingKeys.self)
self.avatarUrl = try container.decodeIfPresent(String.self, forKey: .avatarUrl)
self.username = try container.decodeIfPresent(String.self, forKey: .username)
self.role = try container.decodeIfPresent(String.self, forKey: .role)
}
[...]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment