Created
December 9, 2016 20:18
-
-
Save triage/caa907c3e84ed2d9d7fd0c2c6a8a2e83 to your computer and use it in GitHub Desktop.
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
// | |
// Cachable.swift | |
// CPCoreLibrary | |
// | |
// Created by Dustin Hoffman on 12/8/16. | |
// Copyright © 2016 Classpass. All rights reserved. | |
// | |
import Foundation | |
public protocol Cachable { | |
associatedtype T | |
func cache() | |
static func remove() | |
static var keyForClass: String { get } | |
} | |
public extension Cachable where Self: NSObject { | |
public func cache() { | |
let userDefaults = UserDefaults.standard | |
let data = NSKeyedArchiver.archivedData(withRootObject: self) | |
userDefaults.set(data, forKey:type(of:self).keyForClass) | |
userDefaults.synchronize() | |
} | |
static var keyForClass: String { | |
let className = String(describing: self) | |
return "CPKeyForArchiveClass\(className)" | |
} | |
static var cached: T? { | |
let userDefaults = UserDefaults.standard | |
let data = userDefaults.object(forKey: self.keyForClass) | |
return NSKeyedUnarchiver.unarchiveObject(with: data as! Data) as? T | |
} | |
static func remove() { | |
let userDefaults = UserDefaults.standard | |
userDefaults.removeObject(forKey: self.keyForClass) | |
userDefaults.synchronize() | |
} | |
} | |
class Foo: NSObject, Cachable { | |
typealias T = Foo | |
func omfg() { | |
print("hi") | |
} | |
func foobar() { | |
if let xxx = Foo.cached { | |
xxx.foobar() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment