KObject.m 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // KObject.m
  3. // KacheDemo
  4. //
  5. // Created by jiajun on 7/25/12.
  6. // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
  7. //
  8. #define KCH_OBJ_DATA @"data"
  9. #define KCH_OBJ_LIFE @"life"
  10. #import "KConfig.h"
  11. #import "KObject.h"
  12. #import "KUtil.h"
  13. @interface KObject ()
  14. @end
  15. @implementation KObject
  16. @synthesize object = _object;
  17. #pragma mark - init
  18. - (KObject *)initWithData:(id)aData andLifeDuration:(NSInteger)aDuration
  19. {
  20. self = [super init];
  21. if (self) {
  22. aDuration = (0 >= aDuration) ? KACHE_DEFAULT_LIFE_DURATION : aDuration;
  23. self.object = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
  24. aData, KCH_OBJ_DATA,
  25. [NSString stringWithFormat:@"%d", [KUtil expiredTimestampForLife:aDuration]], KCH_OBJ_LIFE,
  26. nil];
  27. return self;
  28. }
  29. return nil;
  30. }
  31. - (KObject *)initWithDictionary:(NSMutableDictionary *)dict
  32. {
  33. self = [super init];
  34. if (self) {
  35. self.object = dict;
  36. return self;
  37. }
  38. return nil;
  39. }
  40. #pragma - public
  41. - (id)value
  42. {
  43. if ([[self.object allKeys] containsObject:KCH_OBJ_DATA]
  44. && [self.object objectForKey:KCH_OBJ_DATA]) {
  45. return [self.object objectForKey:KCH_OBJ_DATA];
  46. }
  47. return nil;
  48. }
  49. - (NSInteger)expiredTimestamp
  50. {
  51. return [[self.object objectForKey:KCH_OBJ_LIFE] intValue];
  52. }
  53. - (void)updateLifeDuration:(NSInteger)aDuration
  54. {
  55. aDuration = (0 >= aDuration) ? KACHE_DEFAULT_LIFE_DURATION : aDuration;
  56. [self.object setValue:[NSString stringWithFormat:@"%d", [KUtil expiredTimestampForLife:aDuration]]
  57. forKey:KCH_OBJ_LIFE];
  58. }
  59. - (BOOL)expired
  60. {
  61. if ([KUtil nowTimestamp] < [[self.object objectForKey:KCH_OBJ_LIFE] intValue]) {
  62. return NO;
  63. }
  64. return YES;
  65. }
  66. @end