ZYLNetworkCacheManager.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //
  2. // ZYLNetworkCacheManager.m
  3. // NetworkLayerBuild
  4. //
  5. // Created by 翟玉磊 on 2017/9/1.
  6. // Copyright © 2017年 翟玉磊. All rights reserved.
  7. //
  8. #import "ZYLNetworkCacheManager.h"
  9. #pragma mark - ZYLNetworkCache
  10. @interface ZYLNetworkCache ()
  11. @property (nonatomic, strong) id data;
  12. @property (nonatomic, assign) NSUInteger cacheTime;
  13. @property (nonatomic, assign) NSUInteger validTimeInterval;
  14. @end
  15. #define ValidTimeInterval 60
  16. @implementation ZYLNetworkCache
  17. + (instancetype)cacheWithData:(id)data {
  18. return [self cacheWithData:data vaildTimeInterval:ValidTimeInterval];
  19. }
  20. + (instancetype)cacheWithData:(id)data vaildTimeInterval:(NSUInteger)interterval {
  21. ZYLNetworkCache *cache = [ZYLNetworkCache new];
  22. cache.data = data;
  23. cache.cacheTime = [[NSDate date] timeIntervalSince1970];
  24. cache.validTimeInterval = interterval > 0 ? interterval : ValidTimeInterval;
  25. return cache;
  26. }
  27. - (BOOL)isValid {
  28. if (self.data) {
  29. return [[NSDate date] timeIntervalSince1970] - self.cacheTime < self.validTimeInterval;
  30. }
  31. return NO;
  32. }
  33. @end
  34. #pragma mark - ZYLNetworkCacheManager
  35. @interface ZYLNetworkCacheManager ()
  36. @property (nonatomic, strong) NSCache *cache;
  37. @end
  38. @implementation ZYLNetworkCacheManager
  39. + (instancetype)sharedManager {
  40. static ZYLNetworkCacheManager *sharedManager;
  41. static dispatch_once_t onceToken;
  42. dispatch_once(&onceToken, ^{
  43. sharedManager = [[super allocWithZone:NULL] init];
  44. });
  45. return sharedManager;
  46. }
  47. + (instancetype)allocWithZone:(struct _NSZone *)zone {
  48. return [self sharedManager];
  49. }
  50. - (void)configuration {
  51. self.cache = [NSCache new];
  52. self.cache.totalCostLimit = 1024 * 1024 * 20;
  53. }
  54. #pragma mark - Interface
  55. - (void)setObject:(ZYLNetworkCache *)object forKey:(id)key {
  56. [self.cache setObject:object forKey:key];
  57. }
  58. - (void)removeObjectForKey:(id)key {
  59. [self.cache removeObjectForKey:key];
  60. }
  61. - (ZYLNetworkCache *)objectForKey:(id)key {
  62. return [self.cache objectForKey:key];
  63. }
  64. @end