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

Retain cache hits in memory when loaded from disk #110

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
12 changes: 8 additions & 4 deletions AwesomeCache/Cache.swift
Expand Up @@ -235,11 +235,15 @@ open class Cache<T: NSCoding> {

// Otherwise, read from disk
let path = urlForKey(key).path
if fileManager.fileExists(atPath: path) {
return _awesomeCache_unarchiveObjectSafely(path) as? CacheObject
guard
fileManager.fileExists(atPath: path),
let object = _awesomeCache_unarchiveObjectSafely(path) as? CacheObject else {
return nil
}

return nil

// Keep in memory:
cache.setObject(object, forKey: key as NSString)
return object
}

// Deletes an object from disk
Expand Down
15 changes: 15 additions & 0 deletions AwesomeCacheTests/AwesomeCacheTests.swift
Expand Up @@ -30,6 +30,21 @@ class AwesomeCacheTests: XCTestCase {
XCTAssertNotNil(cache.object(forKey: "add"), "Added object should not be nil")
XCTAssertEqual("AddedString", cache.object(forKey: "add")!, "Fetched object should be equal to the inserted object")
}

func testObjectIsRetainedInMemoryWhenLoadedFromDisk() {
let cache = try! Cache<NSString>(name: "testObjectMemoryRetention")

//Add to cache, both in-memory and on-disk:
cache.setObject("AddedString", forKey: "add")

//purge in-memory cache
cache.cache.removeAllObjects()

//load from disk
_ = cache.object(forKey: "add")

XCTAssertTrue(cache.isOnMemory(forKey: "add"), "Cached object should be loaded from disk and retained in memory")
}

func testGetExpiredObjectIfPresent() {
let cache = try! Cache<NSString>(name: "testGetExpiredObject")
Expand Down