Last active
August 29, 2015 14:17
-
-
Save gilesvangruisen/30c95af0d3ad372ecdc0 to your computer and use it in GitHub Desktop.
StorableValue protocol for encoding/decoding a value type and StoredValue object for boxing up a StorableValue to be cached. (Value types can't conform to NSCoding because it's a class-protocol.)
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
| protocol StorableValue { | |
| typealias DecodedType = Self | |
| public static func decode(json: NSData) -> DecodedType? | |
| public func encode() -> NSData | |
| } | |
| final class StoredValue<T: StorableValue>: NSCoding { | |
| private var data = NSData() | |
| init(T: value) { | |
| setValue(value) | |
| } | |
| // Set value | |
| setValue(value: T) { | |
| self.data = value.encode() | |
| } | |
| // Access value | |
| value() -> T? { | |
| return T.decode(data: self.data) | |
| } | |
| // MARK: NSCoding | |
| required init(coder aDecoder: NSCoder) { | |
| self.data = coder.decodeDataObject() | |
| } | |
| func encodeWithCoder(aCoder: NSCoder) { | |
| aCoder.encodeDataObject(self.data) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment