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:
parent
cdb8446c86
commit
2cefb87f20
|
@ -20,8 +20,7 @@ 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) {
|
||||
|
||||
|
@ -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)
|
||||
}
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue