-
Notifications
You must be signed in to change notification settings - Fork 354
Expand file tree
/
Copy pathMemoryCache.swift
More file actions
66 lines (50 loc) · 1.75 KB
/
MemoryCache.swift
File metadata and controls
66 lines (50 loc) · 1.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import Foundation
public class MemoryCache: CacheAware {
public static let prefix = "no.hyper.Cache.Memory"
public var path: String {
return cache.name
}
public var maxSize: UInt = 0 {
didSet(value) {
self.cache.totalCostLimit = Int(maxSize)
}
}
public let cache = NSCache()
public private(set) var writeQueue: dispatch_queue_t
public private(set) var readQueue: dispatch_queue_t
// MARK: - Initialization
public required init(name: String) {
cache.name = "\(MemoryCache.prefix).\(name.capitalizedString)"
writeQueue = dispatch_queue_create("\(cache.name).WriteQueue", DISPATCH_QUEUE_SERIAL)
readQueue = dispatch_queue_create("\(cache.name).ReadQueue", DISPATCH_QUEUE_SERIAL)
}
// MARK: - CacheAware
public func add<T: Cachable>(key: String, object: T, completion: (() -> Void)? = nil) {
dispatch_async(writeQueue) { [weak self] in
guard let weakSelf = self else { return }
weakSelf.cache.setObject(object, forKey: key)
completion?()
}
}
public func object<T: Cachable>(key: String, completion: (object: T?) -> Void) {
dispatch_async(readQueue) { [weak self] in
guard let weakSelf = self else { return }
let cachedObject = weakSelf.cache.objectForKey(key) as? T
completion(object: cachedObject)
}
}
public func remove(key: String, completion: (() -> Void)? = nil) {
dispatch_async(writeQueue) { [weak self] in
guard let weakSelf = self else { return }
weakSelf.cache.removeObjectForKey(key)
completion?()
}
}
public func clear(completion: (() -> Void)? = nil) {
dispatch_async(writeQueue) { [weak self] in
guard let weakSelf = self else { return }
weakSelf.cache.removeAllObjects()
completion?()
}
}
}