Skip to content

Instantly share code, notes, and snippets.

@pmairoldi
Created October 9, 2015 15:53
Show Gist options
  • Save pmairoldi/58d7d14b21db7fbf2e5c to your computer and use it in GitHub Desktop.
Save pmairoldi/58d7d14b21db7fbf2e5c to your computer and use it in GitHub Desktop.
Archiving swift objects
import Foundation
public protocol Archivable {
typealias T
static func decompress(object: AnyObject) -> T?
static func compress(object: T) -> AnyObject
}
public class Archiver<T: Archivable>: NSObject, NSCoding {
private let value: T.T?
private init(_ _value: T.T) {
value = _value
super.init()
}
required public init?(coder aDecoder: NSCoder) {
guard let decodedObject = aDecoder.decodeObject() else {
value = nil
super.init()
return
}
guard let decompressed: T.T = T.decompress(decodedObject) else {
value = nil
super.init()
return
}
value = decompressed
super.init()
}
public func encodeWithCoder(aCoder: NSCoder) {
guard let value = value else {
return
}
aCoder.encodeObject(T.compress(value))
}
static public func archive(object: T.T, toFile path: String) {
NSKeyedArchiver.archiveRootObject(Archiver(object), toFile: path)
}
static public func unarchive(objectWithFile path: String) -> T.T? {
guard let unarchived = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? Archiver else {
return nil
}
return unarchived.value
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment