Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save keitaito/89afd0469315fcdd4312 to your computer and use it in GitHub Desktop.
Save keitaito/89afd0469315fcdd4312 to your computer and use it in GitHub Desktop.
How to conform NSCoding protocol in Swift
// NSCoding Protocol conformed implementation
// Reference: http://stackoverflow.com/questions/20539619/storing-custom-objects-with-core-data
import Foundation
class MyClass: NSObject, NSCoding {
let name: String
init(name: String) {
self.name = name
super.init()
}
// MARK: - NSCoding protocol required methods
required convenience init?(coder aDecoder: NSCoder) {
guard let name = aDecoder.decodeObjectForKey("name") as? String else { return nil }
self.init(name: name)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(name, forKey: "name")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment