LOTAnimationCache.m 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // LOTAnimationCache.m
  3. // Lottie
  4. //
  5. // Created by Brandon Withrow on 1/9/17.
  6. // Copyright © 2017 Brandon Withrow. All rights reserved.
  7. //
  8. #import "LOTAnimationCache.h"
  9. const NSInteger kLOTCacheSize = 50;
  10. @implementation LOTAnimationCache {
  11. NSMutableDictionary *animationsCache_;
  12. NSMutableArray *lruOrderArray_;
  13. }
  14. + (instancetype)sharedCache {
  15. static LOTAnimationCache *sharedCache = nil;
  16. static dispatch_once_t onceToken;
  17. dispatch_once(&onceToken, ^{
  18. sharedCache = [[self alloc] init];
  19. });
  20. return sharedCache;
  21. }
  22. - (instancetype)init {
  23. self = [super init];
  24. if (self) {
  25. animationsCache_ = [[NSMutableDictionary alloc] init];
  26. lruOrderArray_ = [[NSMutableArray alloc] init];
  27. }
  28. return self;
  29. }
  30. - (void)addAnimation:(LOTComposition *)animation forKey:(NSString *)key {
  31. if (lruOrderArray_.count >= kLOTCacheSize) {
  32. NSString *oldKey = lruOrderArray_[0];
  33. [animationsCache_ removeObjectForKey:oldKey];
  34. [lruOrderArray_ removeObject:oldKey];
  35. }
  36. [lruOrderArray_ removeObject:key];
  37. [lruOrderArray_ addObject:key];
  38. [animationsCache_ setObject:animation forKey:key];
  39. }
  40. - (LOTComposition *)animationForKey:(NSString *)key {
  41. if (!key) {
  42. return nil;
  43. }
  44. LOTComposition *animation = [animationsCache_ objectForKey:key];
  45. [lruOrderArray_ removeObject:key];
  46. [lruOrderArray_ addObject:key];
  47. return animation;
  48. }
  49. - (void)clearCache {
  50. [animationsCache_ removeAllObjects];
  51. [lruOrderArray_ removeAllObjects];
  52. }
  53. - (void)removeAnimationForKey:(NSString *)key {
  54. [lruOrderArray_ removeObject:key];
  55. [animationsCache_ removeObjectForKey:key];
  56. }
  57. - (void)disableCaching {
  58. [self clearCache];
  59. animationsCache_ = nil;
  60. lruOrderArray_ = nil;
  61. }
  62. @end