NSCache+BlocksKit.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //
  2. // NSCache+BlocksKit.h
  3. // BlocksKit
  4. //
  5. #import <Foundation/Foundation.h>
  6. /** NSCache with block adding of objects
  7. This category allows you to conditionally add objects to
  8. an instance of NSCache using blocks. Both the normal
  9. delegation pattern and a block callback for NSCache's one
  10. delegate method are allowed.
  11. These methods emulate Rails caching behavior.
  12. Created by [Igor Evsukov](https://github.com/evsukov89) and contributed to BlocksKit.
  13. */
  14. @interface NSCache (BlocksKit)
  15. /** Returns the value associated with a given key. If there is no
  16. object for that key, it uses the result of the block, saves
  17. that to the cache, and returns it.
  18. This mimics the cache behavior of Ruby on Rails. The following code:
  19. @products = Rails.cache.fetch('products') do
  20. Product.all
  21. end
  22. becomes:
  23. NSMutableArray *products = [cache objectForKey:@"products" withGetter:^id{
  24. return [Product all];
  25. }];
  26. @return The value associated with *key*, or the object returned
  27. by the block if no value is associated with *key*.
  28. @param key An object identifying the value.
  29. @param getterBlock A block used to get an object if there is no
  30. value in the cache.
  31. */
  32. - (id)bk_objectForKey:(id)key withGetter:(id (^)(void))getterBlock;
  33. /** Called when an object is about to be evicted from the cache.
  34. This block callback is an analog for the cache:willEviceObject:
  35. method of NSCacheDelegate.
  36. */
  37. @property (nonatomic, copy, setter = bk_setWillEvictBlock:) void (^bk_willEvictBlock)(NSCache *cache, id obj);
  38. @end