Last active
August 29, 2015 14:26
-
-
Save waltflanagan/0af371edbf68e938903a to your computer and use it in GitHub Desktop.
Strongly Typed NSCoding
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public protocol NSCodingKey: RawRepresentable { } | |
extension NSCoder{ | |
func encodeObject<T where T:NSCodingKey, T.RawValue == String>(objv: AnyObject?, forKey key: T) { | |
self.encodeObject(objv, forKey: key.rawValue) | |
} | |
func decodeObjectForKey<T where T:NSCodingKey, T.RawValue == String>(key: T) -> AnyObject?{ | |
return decodeObjectForKey(key.rawValue) | |
} | |
} | |
class Book : NSObject, NSCoding { | |
let title:String | |
let author:String | |
private enum BookKey: String, NSCodingKey { | |
case Title | |
case Author | |
} | |
required init(coder aDecoder: NSCoder) { | |
self.title = aDecoder.decodeObjectForKey(BookKey.Title) as! String | |
self.author = aDecoder.decodeObjectForKey(BookKey.Author) as! String | |
} | |
func encodeWithCoder(aCoder: NSCoder) { | |
aCoder.encodeObject(self.title, forKey: BookKey.Title) | |
aCoder.encodeObject(self.author, forKey: BookKey.Author) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment