9

I need to make a dictionary like NSCache which is thread-safe for keeping a cahce. 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 ? NSMutableDictionary with synchronization ?

Roecrew
  • 1,022
  • 3
  • 17
  • 34
Ali
  • 1,393
  • 2
  • 13
  • 19
  • This would require adding keys to NSMutableSet though when you are caching new things which in turn requires locking. So I'm not sure if this is a better approach than having NSMutableDictionary with locking except that you don't need to lock the set when you are reading from it. – Ali Mar 05 '13 at 16:04
  • That's true, but as I said, `NSCache` has some other properties besides thread-safety that are not as easy to replicate with an `NSMutableDictionary`. – omz Mar 05 '13 at 16:10
  • Got it. Thanks for discussing this. – Ali Mar 05 '13 at 20:13
  • 1
    Does it have to be iterated? Because there is always the `-removeAllObjects` route, or perhaps you could look into `NSDiscardableContent`. – axiixc Apr 23 '13 at 05:15
  • 1
    I thought there would be a allKeys and allValues property in NSCache... makes one wonder why they don't exist. – Jonny Mar 26 '14 at 07:24

1 Answers1

2

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

J. Doe
  • 114
  • 5