Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow manual clear of expired objects #65

Merged
merged 2 commits into from
Jan 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions Source/Shared/BasicHybridCache.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?()
}
}
}
}
31 changes: 31 additions & 0 deletions Tests/iOS/Specs/CacheSpec.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
}
}