Skip to content

Instantly share code, notes, and snippets.

@gilesvangruisen
Last active August 29, 2015 14:17
Show Gist options
  • Select an option

  • Save gilesvangruisen/30c95af0d3ad372ecdc0 to your computer and use it in GitHub Desktop.

Select an option

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.)
//
// StoredValue.swift
// FPAPI
//
// Created by Giles Van Gruisen on 3/20/15.
// Copyright (c) 2015 Remarkable.io. All rights reserved.
//
import Foundation
/**
The StorableValue protocol declares two functions
for encoding and decoding a Swift value type
because NSCoding is restricted to class types.
*/
public protocol StorableValue {
class func decode(decoder: NSCoder) -> Self
func encode(coder: NSCoder)
}
/**
StoredValue defines a generic class defines a
generic class used to encode/decode and box data
from any StorableValue to make caching easier.
*/
final public class StoredValue<T: StorableValue> {
private var mutableData = NSMutableData()
public var data: NSData {
get {
return NSData(data: mutableData)
}
}
public init(value: T) {
encode(value)
}
public init(data: NSData) {
mutableData = NSMutableData(data: data)
}
// Set value
func encode(value: T) {
let archiver = NSKeyedArchiver(forWritingWithMutableData: mutableData)
value.encode(archiver)
archiver.finishEncoding()
}
// Access value
func decode() -> T {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: mutableData)
let value = T.decode(unarchiver)
unarchiver.finishDecoding()
return value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment