TestsTested | ✓ |
LangLanguage | SwiftSwift |
License | MIT |
ReleasedLast Release | Dec 2016 |
SwiftSwift Version | 3.0 |
SPMSupports SPM | ✗ |
Maintained by Zoltán Matók.
Johnny is a caching library written in Swift 3.
Storable
protocolNSCache
Extra
func setImageWithURL
extension on UIImageView, UIButton & NSImageView, optimized for cell reuseJohnny.cache(Date(), key: "FirstStart")
// The type of the retrived value must be explicitly stated for the compiler.
let date: Date? = Johnny.pull("FirstStart")
If you know you are retrieving a large object (> 1.5 MB):
Johnny.pull("4KImage") { (value: UIImage?) in
}
You can set a global prefix that gets attached to the key parameter in every call to enable for example caching of data on a per userID basis.
Johnny.prefix = localUser.userID
Note, that since the protocol uses a static constructor function instead of an initializer, you can extend any class without errors, even if you don’t have access to its source (like Standard library classes)
public protocol Storable {
associatedtype Result
static func fromData(data: NSData) -> Result?
func toData() -> NSData
}
You can cache any collection of items conforming to the Storable protocol (most Stdlib data types already do)
let array: [String] = ["Folsom", "Prison", "Blues"]
let stringSet: Set<String> = ["I've", "been", "everywhere"]
// In case of dictionaries, the value must explicitly conform to Storable (so [String: AnyObject] does not work, while [String: Double] does)
let dictionary: [String: String] = ["first": "Solitary", "second": "man"]
Johnny.cache(array, key: "folsom")
Johnny.cache(stringSet, key: "everywhere")
Johnny.cache(dictionary, key: "solitary")
Due to current Swift limitations, since the Storable protocol has an associatedType
, conformance must be added through an extension. class User: Storable
will not work.
class User {
enum Badassery: String { case Total }
var name: String? = "Johnny"
var uid: Int = 84823682
var badassery = Badassery.Total
}
extension User: Storable {
typealias Result = User
static func fromData(data: NSData) -> User.Result? {
let dict = try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions()) as! [NSObject: AnyObject]
let user = User()
user.uid = dict["identification"] as! Int
user.name = dict["name"] as? String
user.badassery = Badassery(rawValue: dict["badassery"] as! String)!
return user
}
func toData() -> NSData {
let json = ["identification": uid, "name": name, "badasery": badassery.rawValue]
return try! NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions())
}
}
Using it with Johnny:
let johnny: User = User()
Johnny.cache(johnny, key: "John")
let cachedJohn: User = Johnny.pull("John")
CocoaPods
pod 'Johnny'
I’d like to thank the creators of Pantry and Haneke as those projects provided much of the inspiration and some code. Johnny was dreamed up to be the best of both worlds.
Johnny is released under the MIT license. See LICENSE for details.