VLCThumbnailsCache.m 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // VLCThumbnailsCache.m
  3. // VLC for iOS
  4. //
  5. // Created by Gleb on 9/13/13.
  6. // Copyright (c) 2013 VideoLAN. All rights reserved.
  7. //
  8. // Refer to the COPYING file of the official project for license.
  9. //
  10. #import "VLCThumbnailsCache.h"
  11. static NSInteger MaxCacheSize;
  12. static NSMutableArray *_thumbnailCacheIndex = nil;
  13. static NSMutableDictionary *_thumbnailCache = nil;
  14. @implementation VLCThumbnailsCache
  15. #define MAX_CACHE_SIZE_IPHONE 21 // three times the number of items shown on iPhone 5
  16. #define MAX_CACHE_SIZE_IPAD 27 // three times the number of items shown on iPad
  17. +(void)initialize
  18. {
  19. MaxCacheSize = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)?
  20. MAX_CACHE_SIZE_IPAD: MAX_CACHE_SIZE_IPHONE;
  21. // TODO Consider to use NSCache
  22. _thumbnailCache = [[NSMutableDictionary alloc] initWithCapacity:MaxCacheSize];
  23. _thumbnailCacheIndex = [[NSMutableArray alloc] initWithCapacity:MaxCacheSize];
  24. }
  25. + (UIImage *)thumbnailForMediaFile:(MLFile *)mediaFile
  26. {
  27. if (mediaFile == nil || mediaFile.objectID == nil)
  28. return nil;
  29. NSManagedObjectID *objID = mediaFile.objectID;
  30. UIImage *displayedImage = nil;
  31. if ([_thumbnailCacheIndex containsObject:objID]) {
  32. [_thumbnailCacheIndex removeObject:objID];
  33. [_thumbnailCacheIndex insertObject:objID atIndex:0];
  34. displayedImage = [_thumbnailCache objectForKey:objID];
  35. if (!displayedImage && mediaFile.computedThumbnail) {
  36. displayedImage = mediaFile.computedThumbnail;
  37. [_thumbnailCache setObject:displayedImage forKey:objID];
  38. }
  39. } else {
  40. if (_thumbnailCacheIndex.count >= MaxCacheSize) {
  41. [_thumbnailCache removeObjectForKey:[_thumbnailCacheIndex lastObject]];
  42. [_thumbnailCacheIndex removeLastObject];
  43. }
  44. displayedImage = mediaFile.computedThumbnail;
  45. if (displayedImage) {
  46. [_thumbnailCache setObject:displayedImage forKey:objID];
  47. [_thumbnailCacheIndex insertObject:objID atIndex:0];
  48. }
  49. }
  50. return displayedImage;
  51. }
  52. @end