KHolder.m 9.4 KB

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