UIView+WebCacheOperation.m 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. #import "objc/runtime.h"
  10. static char loadOperationKey;
  11. // key is copy, value is weak because operation instance is retained by SDWebImageManager's runningOperations property
  12. // we should use lock to keep thread-safe because these method may not be acessed from main queue
  13. typedef NSMapTable<NSString *, id<SDWebImageOperation>> SDOperationsDictionary;
  14. @implementation UIView (WebCacheOperation)
  15. - (SDOperationsDictionary *)sd_operationDictionary {
  16. @synchronized(self) {
  17. SDOperationsDictionary *operations = objc_getAssociatedObject(self, &loadOperationKey);
  18. if (operations) {
  19. return operations;
  20. }
  21. operations = [[NSMapTable alloc] initWithKeyOptions:NSPointerFunctionsStrongMemory valueOptions:NSPointerFunctionsWeakMemory capacity:0];
  22. objc_setAssociatedObject(self, &loadOperationKey, operations, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  23. return operations;
  24. }
  25. }
  26. - (void)sd_setImageLoadOperation:(nullable id<SDWebImageOperation>)operation forKey:(nullable NSString *)key {
  27. if (key) {
  28. [self sd_cancelImageLoadOperationWithKey:key];
  29. if (operation) {
  30. SDOperationsDictionary *operationDictionary = [self sd_operationDictionary];
  31. @synchronized (self) {
  32. [operationDictionary setObject:operation forKey:key];
  33. }
  34. }
  35. }
  36. }
  37. - (void)sd_cancelImageLoadOperationWithKey:(nullable NSString *)key {
  38. if (key) {
  39. // Cancel in progress downloader from queue
  40. SDOperationsDictionary *operationDictionary = [self sd_operationDictionary];
  41. id<SDWebImageOperation> operation;
  42. @synchronized (self) {
  43. operation = [operationDictionary objectForKey:key];
  44. }
  45. if (operation) {
  46. if ([operation conformsToProtocol:@protocol(SDWebImageOperation)]) {
  47. [operation cancel];
  48. }
  49. @synchronized (self) {
  50. [operationDictionary removeObjectForKey:key];
  51. }
  52. }
  53. }
  54. }
  55. - (void)sd_removeImageLoadOperationWithKey:(nullable NSString *)key {
  56. if (key) {
  57. SDOperationsDictionary *operationDictionary = [self sd_operationDictionary];
  58. @synchronized (self) {
  59. [operationDictionary removeObjectForKey:key];
  60. }
  61. }
  62. }
  63. @end