KHolder.m 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. //
  2. // KHolder.m
  3. // KacheDemo
  4. //
  5. // Created by jiajun on 7/25/12.
  6. // Copyright (c) 2012 __MyCompanyName__. All rights reserved.
  7. //
  8. #define Kache_Objects_Disk_Path @"Kache_objects"
  9. #define DATA_FREE 0
  10. #define DATA_OPERATING 1
  11. #import "KConfig.h"
  12. #import "KHolder.h"
  13. #import "KObject.h"
  14. #import "KUtil.h"
  15. @interface KHolder ()
  16. // 正在进行归档的状态位
  17. @property (assign, atomic) BOOL archiving;
  18. @property (assign, atomic) BOOL cleaning;
  19. @property (strong, nonatomic) NSFileManager *fileManager;
  20. @property (strong, atomic) NSMutableArray *keys;
  21. @property (assign, nonatomic) NSUInteger size;
  22. @property (strong, nonatomic) NSMutableDictionary *objects;
  23. @property (strong, nonatomic) NSString *path;
  24. @property (strong, atomic) NSConditionLock *lock;
  25. // 把数据写到磁盘
  26. - (void)archiveData;
  27. - (void)archiveAllData;
  28. - (void)cleanExpiredObjects;
  29. @end
  30. @implementation KHolder
  31. @synthesize archiving = _archiving;
  32. @synthesize cleaning = _cleaning;
  33. @synthesize fileManager = _fileManager;
  34. // 缓存Key列表
  35. @synthesize keys = _keys;
  36. // 缓存大小
  37. @synthesize size = _size;
  38. // 缓存内容
  39. @synthesize objects = _objects;
  40. @synthesize path = _path;
  41. #pragma mark - init
  42. - (id)init
  43. {
  44. self = [self initWithToken:@"_KacheDefault"];
  45. if (self) {
  46. return self;
  47. }
  48. return nil;
  49. }
  50. - (id)initWithToken:(NSString *)token
  51. {
  52. self = [super init];
  53. if (self) {
  54. self.objects = [[NSMutableDictionary alloc] init];
  55. self.keys = [[NSMutableArray alloc] init];
  56. self.size = 0;
  57. self.lock = [[NSConditionLock alloc] initWithCondition:DATA_OPERATING];
  58. NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
  59. NSString *libDirectory = [paths objectAtIndex:0];
  60. self.path = [libDirectory stringByAppendingPathComponent:[Kache_Objects_Disk_Path stringByAppendingPathExtension:token]];
  61. return self;
  62. }
  63. return nil;
  64. }
  65. #pragma mark - private
  66. - (NSFileManager *)fileManager
  67. {
  68. return [NSFileManager defaultManager];
  69. }
  70. - (void)archiveData
  71. {
  72. self.archiving = YES;
  73. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  74. BOOL isDirectory = NO;
  75. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  76. [self.fileManager createDirectoryAtPath:self.self.path
  77. withIntermediateDirectories:YES
  78. attributes:nil
  79. error:nil];
  80. }
  81. [self.lock lockWhenCondition:DATA_FREE];
  82. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  83. while (0 < [copiedKeys count]) {
  84. // 归档至阈值一半的数据
  85. if ((ARCHIVING_THRESHOLD / 2) >= self.size) {
  86. break;
  87. }
  88. NSString *key = [copiedKeys lastObject];
  89. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  90. NSData *data = [self.objects objectForKey:key];
  91. [data writeToFile:filePath atomically:YES];
  92. self.size -= data.length;
  93. [copiedKeys removeLastObject];
  94. [self.objects removeObjectForKey:key];
  95. }
  96. copiedKeys = nil;
  97. [self.lock unlockWithCondition:DATA_FREE];
  98. self.archiving = NO;
  99. });
  100. }
  101. - (void)archiveAllData
  102. {
  103. self.archiving = YES;
  104. BOOL isDirectory = NO;
  105. if (! [[NSFileManager defaultManager] fileExistsAtPath:self.path isDirectory:&isDirectory]) {
  106. [self.fileManager createDirectoryAtPath:self.self.path
  107. withIntermediateDirectories:YES
  108. attributes:nil
  109. error:nil];
  110. }
  111. NSMutableArray *copiedKeys = [self.keys mutableCopy];
  112. while (0 < [copiedKeys count]) {
  113. NSString *key = [copiedKeys lastObject];
  114. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  115. NSData *data = [self.objects objectForKey:key];
  116. [data writeToFile:filePath atomically:YES];
  117. self.size -= data.length;
  118. [copiedKeys removeLastObject];
  119. [self.objects removeObjectForKey:key];
  120. }
  121. copiedKeys = nil;
  122. self.archiving = NO;
  123. }
  124. - (void)cleanExpiredObjects
  125. {
  126. self.cleaning = YES;
  127. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
  128. if (self.keys && 0 < [self.keys count]) {
  129. [self.lock lock];
  130. for (int i = 0; i < [self.keys count] - 1; i ++) {
  131. NSString *tmpKey = [self.keys objectAtIndex:i];
  132. KObject *leftObject = [self objectForKey:tmpKey];
  133. if ([leftObject expiredTimestamp] < [KUtil nowTimestamp]) {
  134. [self removeObjectForKey:tmpKey];
  135. }
  136. else {
  137. break;
  138. }
  139. }
  140. [self.lock unlockWithCondition:DATA_FREE];
  141. }
  142. self.cleaning = NO;
  143. });
  144. }
  145. #pragma mark - public
  146. - (void)removeObjectForKey:(NSString *)key {
  147. [self.keys removeObject:key];
  148. if ([[self.objects allKeys] containsObject:key]) {
  149. [self.objects removeObjectForKey:key];
  150. }
  151. else {
  152. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  153. [self.fileManager removeItemAtPath:filePath error:nil];
  154. }
  155. }
  156. - (void)setValue:(id)value forKey:(NSString *)key expiredAfter:(NSInteger)duration
  157. {
  158. KObject *object = [[KObject alloc] initWithData:value andLifeDuration:duration];
  159. if (self.archiving) {
  160. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  161. [object.data writeToFile:filePath atomically:YES];
  162. }
  163. else {
  164. [self.objects setValue:object.data forKey:key];
  165. self.size += [object size];
  166. }
  167. // TODO sort the key by expired time.
  168. [self.keys removeObject:key];
  169. if (! self.cleaning && (0 < [self.keys count])) {
  170. [self cleanExpiredObjects];
  171. [self.lock lockWhenCondition:DATA_FREE];
  172. for (int i = [self.keys count] - 1; i >= 0; i --) {
  173. NSString *tmpKey = [self.keys objectAtIndex:i];
  174. KObject *leftObject = [self objectForKey:tmpKey];
  175. // 过期时间越晚
  176. if ([leftObject expiredTimestamp] <= [object expiredTimestamp]) {
  177. if (([self.keys count] - 1) == i) {
  178. [self.keys addObject:key];
  179. }
  180. else {
  181. [self.keys insertObject:key atIndex:i + 1];
  182. }
  183. break;
  184. }
  185. }
  186. [self.lock unlockWithCondition:DATA_FREE];
  187. }
  188. if (! [self.keys containsObject:key]) {
  189. [self.keys insertObject:key atIndex:0];
  190. }
  191. // 超过阈值,归档
  192. if ((! self.archiving)
  193. && 0 < ARCHIVING_THRESHOLD
  194. && ARCHIVING_THRESHOLD < self.size) {
  195. [self archiveData];
  196. }
  197. }
  198. - (id)valueForKey:(NSString *)key
  199. {
  200. KObject *object = [self objectForKey:key];
  201. if (object && ! [object expired]) {
  202. return [object value];
  203. }
  204. // No such object.
  205. return nil;
  206. }
  207. - (KObject *)objectForKey:(NSString *)key
  208. {
  209. if (! [[self.objects allKeys] containsObject:key]) {
  210. NSString *filePath = [self.path stringByAppendingPathComponent:key];
  211. if ([self.fileManager fileExistsAtPath:filePath isDirectory:NO]) {
  212. // 超过阈值直接返回,不装入内存
  213. if ((! self.archiving) && 0 < ARCHIVING_THRESHOLD && ARCHIVING_THRESHOLD < self.size) {
  214. return [[KObject alloc] initWithData:[NSData dataWithContentsOfFile:filePath]];
  215. }
  216. else {
  217. NSData *data = [NSData dataWithContentsOfFile:filePath];
  218. [self.objects setValue:data forKey:key];
  219. self.size += data.length;
  220. data = nil;
  221. [self.fileManager removeItemAtPath:filePath error:nil];
  222. }
  223. }
  224. else {
  225. return nil;
  226. }
  227. }
  228. return [[KObject alloc] initWithData:[self.objects objectForKey:key]];
  229. }
  230. // Convert object to NSDictionary.
  231. - (NSDictionary *)serialize
  232. {
  233. [self archiveAllData];
  234. return [NSDictionary dictionaryWithObjectsAndKeys:
  235. self.keys, @"keys",
  236. [NSString stringWithFormat:@"%d", self.size], @"size",
  237. nil];
  238. }
  239. // Convert NSDictionary to object.
  240. - (void)unserializeFrom:(NSDictionary *)dict
  241. {
  242. if ([[dict allKeys] containsObject:@"keys"]
  243. && [[dict allKeys] containsObject:@"meta"]) {
  244. self.keys = [dict objectForKey:@"keys"];
  245. self.size = [[dict objectForKey:@"size"] intValue];
  246. }
  247. }
  248. @end