KObject.m 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116
  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. @property (strong, nonatomic) NSData *data;
  15. @property (strong, nonatomic) NSMutableDictionary *object;
  16. @end
  17. @implementation KObject
  18. @synthesize object = _object;
  19. @synthesize data = _data;
  20. #pragma mark - init
  21. - (KObject *)initWithData:(id)aData andLifeDuration:(NSInteger)aDuration
  22. {
  23. self = [super init];
  24. if (self) {
  25. aDuration = (0 >= aDuration) ? KACHE_DEFAULT_LIFE_DURATION : aDuration;
  26. self.data = [NSKeyedArchiver archivedDataWithRootObject:[[NSMutableDictionary alloc] initWithObjectsAndKeys:
  27. aData, KCH_OBJ_DATA,
  28. [NSString stringWithFormat:@"%d", [KUtil expiredTimestampForLife:aDuration]], KCH_OBJ_LIFE,
  29. nil]];
  30. return self;
  31. }
  32. return nil;
  33. }
  34. - (KObject *)initWithData:(NSData *)data
  35. {
  36. self = [super init];
  37. if (self) {
  38. self.data = data;
  39. return self;
  40. }
  41. return nil;
  42. }
  43. #pragma - public
  44. - (NSData *)data
  45. {
  46. return _data;
  47. }
  48. - (id)value
  49. {
  50. if (nil == self.object) {
  51. self.object = [NSKeyedUnarchiver unarchiveObjectWithData:self.data];
  52. }
  53. if ([[self.object allKeys] containsObject:KCH_OBJ_DATA]
  54. && [self.object objectForKey:KCH_OBJ_DATA]) {
  55. return [self.object objectForKey:KCH_OBJ_DATA];
  56. }
  57. return nil;
  58. }
  59. - (NSInteger)expiredTimestamp
  60. {
  61. if (nil == self.object) {
  62. self.object = [NSKeyedUnarchiver unarchiveObjectWithData:self.data];
  63. }
  64. return [[self.object objectForKey:KCH_OBJ_LIFE] intValue];
  65. }
  66. - (void)updateLifeDuration:(NSInteger)aDuration
  67. {
  68. if (nil == self.object) {
  69. self.object = [NSKeyedUnarchiver unarchiveObjectWithData:self.data];
  70. }
  71. aDuration = (0 >= aDuration) ? KACHE_DEFAULT_LIFE_DURATION : aDuration;
  72. [self.object setValue:[NSString stringWithFormat:@"%d", [KUtil expiredTimestampForLife:aDuration]]
  73. forKey:KCH_OBJ_LIFE];
  74. }
  75. - (BOOL)expired
  76. {
  77. if (nil == self.object) {
  78. self.object = [NSKeyedUnarchiver unarchiveObjectWithData:self.data];
  79. }
  80. if ([KUtil nowTimestamp] < [[self.object objectForKey:KCH_OBJ_LIFE] intValue]) {
  81. return NO;
  82. }
  83. return YES;
  84. }
  85. - (NSUInteger)size
  86. {
  87. return _data.length;
  88. }
  89. @end