ImageCacheLRU.m 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. //
  2. // ImageCacheLRU.m
  3. // LenzCameraNativeModuleForRN
  4. //
  5. // Created by 王昭威 on 2023/1/23.
  6. //
  7. #import "ImageCacheLRU.h"
  8. @interface ImageCacheLRU ()
  9. @property (nonatomic, strong) NSMutableDictionary<NSString*, ImageCacheLRUNode*>* hashTable;
  10. @end
  11. @implementation ImageCacheLRU
  12. - (instancetype)init{
  13. self = [super init];
  14. if(self){
  15. _head = [[ImageCacheLRUNode alloc] initWithImage:nil key:@""];
  16. _tail = [[ImageCacheLRUNode alloc] initWithImage:nil key:@""];
  17. _head.next = _tail;
  18. _tail.previous = _head;
  19. _hashTable = [[NSMutableDictionary alloc] init];
  20. }
  21. return self;
  22. }
  23. - (UIImage *)queryByKey:(NSString *)key{
  24. return [self.hashTable objectForKey:key].image;
  25. }
  26. - (void)insertByKey:(NSString *)key image:(UIImage *)image{
  27. ImageCacheLRUNode* node = self.hashTable[key];
  28. if(node != nil){
  29. ImageCacheLRUNode* previous = node.previous;
  30. ImageCacheLRUNode* next = node.next;
  31. previous.next = next;
  32. next.previous = previous;
  33. }
  34. else{
  35. node = [[ImageCacheLRUNode alloc] initWithImage:image key:key];
  36. [self.hashTable setObject:node forKey:key];
  37. }
  38. node.previous = self.head;
  39. node.next = self.head.next;
  40. self.head.next = node;
  41. node.next.previous = node;
  42. if([self.hashTable count] > 10){
  43. ImageCacheLRUNode* toBeRemoved = self.hashTable[self.tail.previous.key];
  44. if(self.tail.previous.key != nil){
  45. [self.hashTable removeObjectForKey:self.tail.previous.key];
  46. }
  47. ImageCacheLRUNode* previous = toBeRemoved.previous;
  48. ImageCacheLRUNode* next = toBeRemoved.next;
  49. previous.next = next;
  50. next.previous = previous;
  51. toBeRemoved.previous = nil;
  52. toBeRemoved.next = nil;
  53. }
  54. }
  55. @end
  56. @implementation ImageCacheLRUNode
  57. - (instancetype)initWithImage:(UIImage *)image key:(nonnull NSString *)key{
  58. self = [super init];
  59. if(self){
  60. _image = image;
  61. _previous = nil;
  62. _next = nil;
  63. _key = [key copy];
  64. }
  65. return self;
  66. }
  67. @end