Created
October 9, 2015 15:53
-
-
Save pmairoldi/58d7d14b21db7fbf2e5c to your computer and use it in GitHub Desktop.
Archiving swift objects
This file contains 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 | |
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