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
| import Foundation | |
| /** | |
| The StorableValue protocol declares two functions for | |
| encoding and decoding a Swift data structure to NSData | |
| */ | |
| protocol StorableValue { | |
| typealias DecodedType = Self | |
| class func decode(json: NSData) -> Self? | |
| //func encode() -> NSData | |
| } | |
| /** | |
| The StoredValue final class defines an NSCoding | |
| conforming object used to encode/decode and box | |
| a StorableValue so that it may be archived and | |
| unarchived to/from any NSData cache. | |
| */ | |
| final class StoredValue<T: StorableValue>: NSObject, NSCoding { | |
| private var data = NSData() | |
| convenience init(value: T) { | |
| self.init() | |
| encode(value) | |
| } | |
| // MARK: NSCoding | |
| convenience init(coder aDecoder: NSCoder) { | |
| self.init() | |
| self.data = aDecoder.decodeDataObject()! | |
| } | |
| func encodeWithCoder(aCoder: NSCoder) { | |
| aCoder.encodeDataObject(self.data) | |
| } | |
| // Set value | |
| func encode(value: T) { | |
| self.data = value.encode() | |
| } | |
| // Access value | |
| func decode() -> T? { | |
| return T.decode(self.data) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment