I need to make a dictionary like NSCache which is thread-safe for keeping a cache. However, once in a while, I would need to refresh the contents of the Cache. NSCache does not provide a method to iterate over its keys. What would be the alternative here? Using NSMutableDictionary with synchronization?
How to iterate over NSCache keys
Asked Answered
NSCache doesn't have such API. So, you should implement your own cache using NSMutaleDictionary or NSMapTable. The main idea is to track order of added objects and remove the older if countLimit is exceeded. This can be done using some ordered structure for storing keys in order of adding, e.g. NSMutableArray. Also, you should track memory warnings and cleanup you cache.
For thread-safety you can use any lock that you like (@synchronized, NSLock, etc.). And you definitely should take keyEnumerator and objectEnumerator from copy of your mutable storage.
You can look at thread-safe implementation with ability to iterate through keys and objects: VSCache
© 2022 - 2024 — McMap. All rights reserved.
NSCache
has some other properties besides thread-safety that are not as easy to replicate with anNSMutableDictionary
. – Evangelineevangelism-removeAllObjects
route, or perhaps you could look intoNSDiscardableContent
. – Dysgenic