UIView+WebCacheOperation.m 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. * This file is part of the SDWebImage package.
  3. * (c) Olivier Poitrey <rs@dailymotion.com>
  4. *
  5. * For the full copyright and license information, please view the LICENSE
  6. * file that was distributed with this source code.
  7. */
  8. #import "UIView+WebCacheOperation.h"
  9. #if SD_UIKIT || SD_MAC
  10. #import "objc/runtime.h"
  11. static char loadOperationKey;
  12. typedef NSMutableDictionary<NSString *, id> SDOperationsDictionary;
  13. @implementation UIView (WebCacheOperation)
  14. - (SDOperationsDictionary *)operationDictionary {
  15. SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
  16. if (operations) {
  17. return operations;
  18. }
  19. operations = [NSMutableDictionary dictionary];
  20. objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  21. return operations;
  22. }
  23. - (void)sd_setImageLoadOperation:(nullable id)operation forKey:(nullable NSString *)key {
  24. if (key) {
  25. [self sd_cancelImageLoadOperationWithKey:key];
  26. if (operation) {
  27. SDOperationsDictionary *operationDictionary = [self operationDictionary];
  28. operationDictionary[key] = operation;
  29. }
  30. }
  31. }
  32. - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
  33. // Cancel in progress downloader from queue
  34. SDOperationsDictionary *operationDictionary = [self operationDictionary];
  35. id operations = operationDictionary[key];
  36. if (operations) {
  37. if ([operations isKindOfClass:[NSArray class]]) {
  38. for (id <SDWebImageOperation> operation in operations) {
  39. if (operation) {
  40. [operation cancel];
  41. }
  42. }
  43. } else if ([operations conformsToProtocol:@protocol(SDWebImageOperation)]){
  44. [(id<SDWebImageOperation>) operations cancel];
  45. }
  46. [operationDictionary removeObjectForKey:key];
  47. }
  48. }
  49. - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key {
  50. if (key) {
  51. SDOperationsDictionary *operationDictionary = [self operationDictionary];
  52. [operationDictionary removeObjectForKey:key];
  53. }
  54. }
  55. @end
  56. #endif