How to iterate over NSCache keys

北城余情 提交于 2019-12-23 07:38:18

问题


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 ?


回答1:


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



来源:https://stackoverflow.com/questions/15213261/how-to-iterate-over-nscache-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!