diff --git a/README.md b/README.md index 34c43b45..3cbc59a5 100644 --- a/README.md +++ b/README.md @@ -207,6 +207,9 @@ cache.add("string", object: "This is a string") // A provided expiry date will be applied to the item cache.add("string", object: "This is a string", expiry: .date(Date().addingTimeInterval(100000))) + +// Clear expired objects +cache.clearExpired() ``` ### Cachable protocol diff --git a/Source/Shared/BasicHybridCache.swift b/Source/Shared/BasicHybridCache.swift index ee24ce4b..2f68dde4 100644 --- a/Source/Shared/BasicHybridCache.swift +++ b/Source/Shared/BasicHybridCache.swift @@ -123,4 +123,22 @@ public class BasicHybridCache: NSObject { } } } + + /** + Clears all expired objects from front and back storages. + + - Parameter completion: Completion closure to be called when the task is done + */ + public func clearExpired(_ completion: (() -> Void)? = nil) { + frontStorage.clearExpired { [weak self] in + guard let weakSelf = self else { + completion?() + return + } + + weakSelf.backStorage.clearExpired() { + completion?() + } + } + } } diff --git a/Tests/iOS/Specs/CacheSpec.swift b/Tests/iOS/Specs/CacheSpec.swift index 28658919..27f665db 100644 --- a/Tests/iOS/Specs/CacheSpec.swift +++ b/Tests/iOS/Specs/CacheSpec.swift @@ -140,6 +140,37 @@ class CacheSpec: QuickSpec { self.waitForExpectations(timeout: 8.0, handler:nil) } } + + describe("#clearExpired") { + it("clears expired objects from memory and disk cache") { + let expectation1 = self.expectation(description: "Clear If Expired Expectation") + let expectation2 = self.expectation(description: "Don't Clear If Not Expired Expectation") + + let expiry1: Expiry = .date(Date().addingTimeInterval(-100000)) + let expiry2: Expiry = .date(Date().addingTimeInterval(100000)) + + let key1 = "key1" + let key2 = "key2" + + cache.add(key1, object: object, expiry: expiry1) { + cache.add(key2, object: object, expiry: expiry2) { + cache.clearExpired() { + cache.object(key1) { (receivedObject: User?) in + expect(receivedObject).to(beNil()) + expectation1.fulfill() + } + + cache.object(key2) { (receivedObject: User?) in + expect(receivedObject).toNot(beNil()) + expectation2.fulfill() + } + } + } + } + + self.waitForExpectations(timeout: 5.0, handler:nil) + } + } } } }