Create ArticleCache, which wraps a weak-to-weak NSMapTable. An article is cached for as long as there’s an external (outside-the-cache) reference to the article.

This commit is contained in:
Brent Simmons 2017-08-23 21:30:28 -07:00
parent cdb8446c86
commit 2cefb87f20
1 changed files with 39 additions and 3 deletions

View File

@ -20,9 +20,8 @@ final class ArticlesTable: DatabaseTable {
private let authorsLookupTable: DatabaseLookupTable
private let attachmentsLookupTable: DatabaseLookupTable
private let tagsLookupTable: DatabaseLookupTable
// private let cachedArticles: NSMapTable<NSString, Article> = NSMapTable.weakToWeakObjects()
private let articleCache = ArticleCache()
init(name: String) {
self.name = name
@ -157,3 +156,40 @@ final class ArticlesTable: DatabaseTable {
// }
//}
private struct ArticleCache {
// Main thread only.
// The cache contains a given article only until all outside references are gone.
// Cache key is articleID.
private let articlesMapTable: NSMapTable<NSString, Article> = NSMapTable.weakToWeakObjects()
func uniquedArticles(_ articles: Set<Article>) -> Set<Article> {
var articlesToReturn = Set<Article>()
for article in articles {
let articleID = article.articleID
if let cachedArticle = cachedArticle(for: articleID) {
articlesToReturn.insert(cachedArticle)
}
else {
articlesToReturn.insert(article)
addToCache(article)
}
}
return articlesToReturn
}
private func cachedArticle(for articleID: String) -> Article? {
return articlesMapTable.object(forKey: articleID as NSString)
}
private func addToCache(_ article: Article) {
articlesMapTable.setObject(article, forKey: article.articleID as NSString)
}
}