/BlocksKit/NSCache+BlocksKit.m

http://github.com/zwaldowski/BlocksKit · Objective C · 57 lines · 36 code · 17 blank · 4 comment · 5 complexity · 2fa90e7a36d640c213f3de936bbe5368 MD5 · raw file

  1. //
  2. // NSCache+BlocksKit.m
  3. // BlocksKit
  4. //
  5. #import "NSCache+BlocksKit.h"
  6. #import "A2BlockDelegate+BlocksKit.h"
  7. #pragma mark Custom delegate
  8. @interface A2DynamicNSCacheDelegate : A2DynamicDelegate
  9. @end
  10. @implementation A2DynamicNSCacheDelegate
  11. - (void)cache:(NSCache *)cache willEvictObject:(id)obj {
  12. id realDelegate = self.realDelegate;
  13. if (realDelegate && [realDelegate respondsToSelector:@selector(cache:willEvictObject:)])
  14. [realDelegate cache:cache willEvictObject:obj];
  15. void (^orig)(NSCache *, id) = [self blockImplementationForMethod:_cmd];
  16. if (orig)
  17. orig(cache, obj);
  18. }
  19. @end
  20. #pragma mark Category
  21. @implementation NSCache (BlocksKit)
  22. @dynamic willEvictBlock;
  23. + (void)load {
  24. @autoreleasepool {
  25. [self registerDynamicDelegate];
  26. [self linkCategoryBlockProperty:@"willEvictBlock" withDelegateMethod:@selector(cache:willEvictObject:)];
  27. }
  28. }
  29. #pragma mark Methods
  30. - (id)objectForKey:(id)key withGetter:(BKReturnBlock)block {
  31. id object = [self objectForKey:key];
  32. if (object)
  33. return object;
  34. if (block) {
  35. object = block();
  36. [self setObject:object forKey:key];
  37. }
  38. return object;
  39. }
  40. @end