QNLruCache.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // QNLruCache.m
  3. // HappyDNS
  4. //
  5. // Created by bailong on 16/7/5.
  6. // Copyright © 2016年 Qiniu Cloud Storage. All rights reserved.
  7. //
  8. #import "QNLruCache.h"
  9. @interface QNLruCache ()
  10. @property (nonatomic, readonly) NSUInteger limit;
  11. @property (nonatomic, readonly) NSMutableDictionary* cache;
  12. @property (nonatomic, readonly) NSMutableArray* list;
  13. @end
  14. @interface _QNElement : NSObject
  15. @property (nonatomic, readonly, strong) NSString* key;
  16. @property (nonatomic, strong) id obj;
  17. - (instancetype)initObject:(id)obj forKey:(NSString*)key;
  18. @end
  19. @implementation _QNElement
  20. - (instancetype)initObject:(id)obj forKey:(NSString*)key {
  21. if (self = [super init]) {
  22. _key = key;
  23. _obj = obj;
  24. }
  25. return self;
  26. }
  27. @end
  28. @implementation QNLruCache
  29. - (instancetype)init:(NSUInteger)limit {
  30. if (self = [super init]) {
  31. _limit = limit;
  32. _cache = [NSMutableDictionary new];
  33. _list = [NSMutableArray new];
  34. }
  35. return self;
  36. }
  37. - (void)removeAllObjects {
  38. [_cache removeAllObjects];
  39. [_list removeAllObjects];
  40. }
  41. - (void)removeObjectForKey:(NSString*)key {
  42. _QNElement* obj = [_cache objectForKey:key];
  43. if (obj == nil) {
  44. return;
  45. }
  46. [_cache removeObjectForKey:key];
  47. [_list removeObjectIdenticalTo:obj];
  48. }
  49. - (id)objectForKey:(NSString*)key {
  50. _QNElement* obj = [_cache objectForKey:key];
  51. if (obj != nil) {
  52. [_list removeObjectIdenticalTo:obj];
  53. [_list insertObject:obj atIndex:0];
  54. }
  55. return obj.obj;
  56. }
  57. - (void)setObject:(id)obj forKey:(NSString*)key {
  58. _QNElement* old = [_cache objectForKey:key];
  59. if (old) {
  60. old.obj = obj;
  61. [_list removeObjectIdenticalTo:old];
  62. [_list insertObject:old atIndex:0];
  63. return;
  64. } else if (_list.count == _limit) {
  65. old = [_list lastObject];
  66. [_list removeLastObject];
  67. [_cache removeObjectForKey:old.key];
  68. }
  69. _QNElement* newElement = [[_QNElement alloc] initObject:obj forKey:key];
  70. [_cache setObject:newElement forKey:key];
  71. [_list insertObject:newElement atIndex:0];
  72. }
  73. @end